Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ActiveRecord:按属性唯一_Activerecord_Ruby On Rails 4 - Fatal编程技术网

ActiveRecord:按属性唯一

ActiveRecord:按属性唯一,activerecord,ruby-on-rails-4,Activerecord,Ruby On Rails 4,我正在尝试筛选ActiveRecord\u AssociationRelations,使其按父id唯一 所以,我想要一个这样的列表: [#<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:

我正在尝试筛选ActiveRecord\u AssociationRelations,使其按父id唯一

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

[#<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)

我觉得这就是你想要的。这将返回具有给定父项id的第一个条目。如果您想要最后一个条目,则必须在子查询中对结果重新排序,然后使用组。

对于我来说,在Rails 3.2和Postgresql中,Foo.group:bar适用于简单查询,但如果其中有where子句,则会给我一个错误

 irb> Message.where(receiver_id: 434).group(:sender_id)
 => PG::GroupingError: ERROR:  column "messages.id" must appear in the
    GROUP BY clause or be used in an aggregate function
我最后指定了一个SQL“DISTINCT ON”子句来选择。在消息类中,我具有以下作用域:

 scope :latest_from_each_sender, -> { order("sender_id ASC, created_at DESC").select('DISTINCT ON ("sender_id") *') }
用法:

 irb> Message.where(receiver_id: 434).latest_from_each_sender

谢谢,这正是我想要的。