如何找到在ActiveRecord的比原来的其他重复的记录 [英] How to find duplicate records in ActiveRecord other than original one

查看:109
本文介绍了如何找到在ActiveRecord的比原来的其他重复的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Rails 4,红宝石2中,MySQL

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.

这是这样我就可以 update_attributes的(:重复=>真)关于这些记录,并保留原未标记为重复

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

您可能会说,我要找 UNIQ *我不希望UNIQ值相反,我希望所有的事实后没有uniq的值。我不希望其具有一个重复的全部的值,因为这将包括原来的。

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.

我不介意使用纯SQL或红宝石,但我会preFER使用活动记录,以保持它Railsy。

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

假设表被称为信息,我们正在寻找那些领域telephone_number是一样的。我会留下记录1单独标记2,3和4重复=真。

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.

* 如果我想UNIQ我可以做类似的查找重复保存在Ruby中哈希

* 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.

推荐答案

我假设你的查询将返回所有信息有在数组b中的同一个电话号码。然后,您可以使用

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

这需要的第一个元素关的B阵列。然后,您可以继续使用原来的想法 update_attributes的(:重复=>真)

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

这篇关于如何找到在ActiveRecord的比原来的其他重复的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆