ActiveRecord中如何确保属性值的唯一性?

更新于
2026-10-09 19:50:59
3阅读来源:SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计287个文字,预计阅读时间需要2分钟。

ActiveRecord中如何确保属性值的唯一性?

我尝试通过父ID过滤ActiveRecord_AssociationRelations,这是唯一的。所以,我想创建一个这样的列表:[ ]

我试图通过父ID过滤ActiveRecord_AssociationRelations是唯一的.

所以,我想要一个这样的列表:

[#<Message id: 25, posted_by_id: 3, posted_at: "2014-10-30 06:02:47", parent_id: 20, content: "This is a comment", created_at: "2014-10-30 06:02:47", updated_at: "2014-10-30 06:02:47">, #<Message id: 23, posted_by_id: 3, posted_at: "2014-10-28 16:11:02", parent_id: 20, content: "This is another comment", created_at: "2014-10-28 16:11:02", updated_at: "2014-10-28 16:11:02">]}

要归还:

[#<Message id: 25, posted_by_id: 3, posted_at: "2014-10-30 06:02:47", parent_id: 20, content: "This is a comment", created_at: "2014-10-30 06:02:47", updated_at: "2014-10-30 06:02:47">]

我尝试了各种技术,包括:

ActiveRecord中如何确保属性值的唯一性?

@messages.uniq(&:parent_id) # returns the same list (with duplicate parent_ids) @messages.select(:parent_id).distinct # returns [#<Message id: nil, parent_id: 20>]

和uniq_by已从Rails 4.1中删除.

你有没有尝试过

group(:parent_id)

这听起来像是你所追求的.这确实返回给定parent_id的第一个条目.如果您想要最后一个条目,则必须在子查询中重新排序结果,然后使用该组.

本文共计287个文字,预计阅读时间需要2分钟。

ActiveRecord中如何确保属性值的唯一性?

我尝试通过父ID过滤ActiveRecord_AssociationRelations,这是唯一的。所以,我想创建一个这样的列表:[ ]

我试图通过父ID过滤ActiveRecord_AssociationRelations是唯一的.

所以,我想要一个这样的列表:

[#<Message id: 25, posted_by_id: 3, posted_at: "2014-10-30 06:02:47", parent_id: 20, content: "This is a comment", created_at: "2014-10-30 06:02:47", updated_at: "2014-10-30 06:02:47">, #<Message id: 23, posted_by_id: 3, posted_at: "2014-10-28 16:11:02", parent_id: 20, content: "This is another comment", created_at: "2014-10-28 16:11:02", updated_at: "2014-10-28 16:11:02">]}

要归还:

[#<Message id: 25, posted_by_id: 3, posted_at: "2014-10-30 06:02:47", parent_id: 20, content: "This is a comment", created_at: "2014-10-30 06:02:47", updated_at: "2014-10-30 06:02:47">]

我尝试了各种技术,包括:

ActiveRecord中如何确保属性值的唯一性?

@messages.uniq(&:parent_id) # returns the same list (with duplicate parent_ids) @messages.select(:parent_id).distinct # returns [#<Message id: nil, parent_id: 20>]

和uniq_by已从Rails 4.1中删除.

你有没有尝试过

group(:parent_id)

这听起来像是你所追求的.这确实返回给定parent_id的第一个条目.如果您想要最后一个条目,则必须在子查询中重新排序结果,然后使用该组.