查找所有具有重复名称的用户

2024-05-03

我有具有名字和姓氏字段的用户,我需要做一个 ruby​​ 查找根据名字和姓氏具有重复帐户的所有用户。例如,我想要一个查找功能,可以搜索所有其他用户,并查找是否有任何用户具有相同的姓名和电子邮件。我在想像这样的嵌套循环

User.all.each do |user|
 //maybe another loop to search through all the users and maybe if a match occurs put that user in an array
end

有没有更好的办法


通过首先找出重复的数据是什么,您可以大大缩小搜索范围。例如,假设您想要查找多次使用的名字和电子邮件的每个组合。

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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

查找所有具有重复名称的用户 的相关文章

随机推荐