Find duplicate entry for any 3 common attributes

My RoR project has a Customer model with 10 attributes. Now I want to find those customers who have at least three common attributes. How can I make this request efficiently?

Perhaps this solution:

Customer.select([:first_name,:last_name,:language]). group(:first_name,:last_name,:language).having("count(*) > 1") 

But this solution requires too many combinations to verify. Please help with a better solution.

Thanks! In Advance.

+5
source share
1 answer

This is the best I can think of so far. Also not a SQL solution.

 # Arrange a 3-items combination of columns, removed id and timestamps triplets = Customer.column_names.reject {|column| column == "id" || column == "created_at" || column == "updated_at"}.combination(3).to_a #Group All records by same item values for each 3-items combination all = Customer.all res = triplets.map do|t| all.to_a.group_by {|c| [ {t[0] => c.send(t[0].to_sym)}, { t[1] => c.send(t[1].to_sym) }, {t[2] => c.send(t[2].to_sym)} ]} end # removed combinations with only 1 record final_result = res.map {|h1| h1.reject { |k, v| v.count <= 1}} # There you have customer with 3 attributes common combinations 
0
source

All Articles