如何查找不重复的记录

时间:2016-10-12 11:12:18

标签: ruby-on-rails

我有一张表可能会有重复的记录。

 id: 24,
  name: "vamsi",
  mobile: "7639817688",
  company: "digi",
  requirement: "mobile app",
  created_at: Wed, 12 Oct 2016 11:05:33 UTC +00:00,
  updated_at: Wed, 12 Oct 2016 11:05:33 UTC +00:00,
  email_sent: false>,
 #<Contact:0x00000006d7a4f0
  id: 25,
  name: "vamsi",
  mobile: "7639817688",
  company: "digi",
  requirement: "mobile app",
  created_at: Wed, 12 Oct 2016 11:05:57 UTC +00:00,
  updated_at: Wed, 12 Oct 2016 11:05:57 UTC +00:00,
  email_sent: false>]

现在我想找到email_sent为false的唯一记录。我试过这个 Contact.where(email_sent: false).distinct

Contact Load (0.4ms)  SELECT DISTINCT "contacts".* FROM "contacts" WHERE "contacts"."email_sent" = $1  [["email_sent", false]]
=> [#<Contact:0x00000006a1a698
  id: 25,
  name: "vamsi",
  mobile: "7639817688",
  company: "digi",
  requirement: "mobile app",
  created_at: Wed, 12 Oct 2016 11:05:57 UTC +00:00,
  updated_at: Wed, 12 Oct 2016 11:05:57 UTC +00:00,
  email_sent: false>,
 #<Contact:0x00000006a1a418
  id: 24,
  name: "vamsi",
  mobile: "7639817688",
  company: "digi",
  requirement: "mobile app",
  created_at: Wed, 12 Oct 2016 11:05:33 UTC +00:00,
  updated_at: Wed, 12 Oct 2016 11:05:33 UTC +00:00,
  email_sent: false>]

但我不想要2条记录,因为两条记录都相同。我希望只有一个人能够出现。有什么方法可以解决这个问题。

2 个答案:

答案 0 :(得分:0)

使用where:

后,通过email_sent尝试分组
Contact.where(email_sent: false).group(:email_sent)

答案 1 :(得分:0)

第一部分,模型应该有验证,以便这些类型的数据不会被存储

可以通过此

完成

validates_uniqueness_of :name, scope: [:mobile, :requirement, :company]

第二部分,如果你想查询类似上面的场景。你必须这样做

Contact.select(:name, :company, :mobile, :requirement).where(email_sent: false).distinct将成为查询

ps:从问题中的所有评论中找到答案