How to find duplicate records in ActiveRecord other than original one

∥☆過路亽.° 提交于 2019-12-13 03:17:42

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/26430049/how-to-find-duplicate-records-in-activerecord-other-than-original-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!