LpLrich
LpLrich

Reputation: 2533

How to find duplicate records in ActiveRecord other than original one

Using Rails 4, Ruby 2, MySql

I would like to find all the records in my database which are repeats of another record - but not the original record itself.

This is so I can update_attributes(:duplicate => true) on each of these records and leave the original one not marked as a duplicate.

You could say that I am looking for the opposite of Uniq* I don't want the Uniq values, I want all the values which are not uniq after the fact. I don't want all values which have a duplicate as that would include the original.

I don't mind using pure SQL or Ruby for this but I would prefer to use active record to keep it Railsy.

Let's say the table is called "Leads" and we are looking for those where the field "telephone_number" is the same. I would leave record 1 alone and mark 2,3 and 4 as duplicate = true.

* If I wanted the opposite of Uniq I could do something like Find keep duplicates in Ruby hashes

b = a.group_by { |h| h[:telephone_number] }.values.select { |a| a.size > 1 }.flatten

But that is all the records, I want all the duplicated ones other than the original one I'm comparing it to.

Upvotes: 0

Views: 1195

Answers (1)

sabrams
sabrams

Reputation: 1128

I'm assuming your query returns all 'Leads' that have the same telephone number in an array b. You can then use

b = b.shift

which takes the first element off of the b array. Then you can continue with your original thought update_attributes(:duplicate => true)

Upvotes: 1

Related Questions