ActiveRecord的属性唯一性如何确保在数据库中不会重复?

2026-04-11 15:311阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

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

ActiveRecord的属性唯一性如何确保在数据库中不会重复?

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

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

ActiveRecord的属性唯一性如何确保在数据库中不会重复?

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

[#<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">]

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

@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的第一个条目.如果您想要最后一个条目,则必须在子查询中重新排序结果,然后使用该组.

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

ActiveRecord的属性唯一性如何确保在数据库中不会重复?

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

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

ActiveRecord的属性唯一性如何确保在数据库中不会重复?

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

[#<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">]

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

@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的第一个条目.如果您想要最后一个条目,则必须在子查询中重新排序结果,然后使用该组.