通过首先找出重复的数据是什么,您可以大大缩小搜索范围。例如,假设您想要查找多次使用的名字和电子邮件的每个组合。
User.find(:all, :group => [:first, :email], :having => "count(*) > 1" )
这将返回一个包含每个重复记录之一的数组。由此,假设其中一位返回的用户有“Fred”和“[电子邮件受保护] /cdn-cgi/l/email-protection" 那么您可以仅搜索具有这些值的用户来查找所有受影响的用户。
从中得到的回报find
将类似于以下内容。请注意,该数组仅包含每组重复用户的一条记录。
[#<User id: 3, first: "foo", last: "barney", email: "[email protected] /cdn-cgi/l/email-protection", created_at: "2010-12-30 17:14:43", updated_at: "2010-12-30 17:14:43">,
#<User id: 5, first: "foo1", last: "baasdasdr", email: "[email protected] /cdn-cgi/l/email-protection", created_at: "2010-12-30 17:20:49", updated_at: "2010-12-30 17:20:49">]
例如,该数组中的第一个元素显示一个具有“foo”和“[电子邮件受保护] /cdn-cgi/l/email-protection”。其余的可以根据需要通过查找从数据库中提取。
> User.find(:all, :conditions => {:email => "[email protected] /cdn-cgi/l/email-protection", :first => "foo"})
=> [#<User id: 1, first: "foo", last: "bar", email: "[email protected] /cdn-cgi/l/email-protection", created_at: "2010-12-30 17:14:28", updated_at: "2010-12-30 17:14:28">,
#<User id: 3, first: "foo", last: "barney", email: "[email protected] /cdn-cgi/l/email-protection", created_at: "2010-12-30 17:14:43", updated_at: "2010-12-30 17:14:43">]
而且您似乎还希望为代码添加一些更好的验证,以防止将来出现重复。
Edit:
如果你需要使用大锤子find_by_sql
,因为Rails 2.2及更早版本不支持:having
with find
,以下内容应该可以工作并为您提供与我上面描述的相同的数组。
User.find_by_sql("select * from users group by first,email having count(*) > 1")