Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: Unique by attribute

I am trying to filter ActiveRecord_AssociationRelations to be unique by parent id.

So, I'd like a list like this:

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

to return this:

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

I've tried various techniques including:

@messages.uniq(&:parent_id) # returns the same list (with duplicate parent_ids)

@messages.select(:parent_id).distinct # returns [#<Message id: nil, parent_id: 20>]

and uniq_by has been removed from Rails 4.1.

like image 423
user3281384 Avatar asked Sep 11 '26 11:09

user3281384


1 Answers

Have you tried

group(:parent_id)

It sounds to me like that is what you are after. This does return the first entry with the given parent_id. If you want the last entry you will have to reorder the result in a subquery and then use the group.

like image 90
Albin Avatar answered Sep 15 '26 12:09

Albin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!