我试图通过父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:
所以,我想要一个这样的列表:
[#<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的第一个条目.如果您想要最后一个条目,则必须在子查询中重新排序结果,然后使用该组.