Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails select distinct association from collection

Let's say I have a model, Post, and a model, User. Given a collection of posts (@posts), how can I get the unique authors?

This works, but is terrible for obvious reasons: @posts.map(&:author).uniq(&:id).

A slightly better method is: User.where(id: @posts.pluck(:author_id)).

Is there a better way?

like image 220
Steven Jeffries Avatar asked Oct 20 '25 09:10

Steven Jeffries


1 Answers

User.where(id: @posts.select('distinct author_id'))

OR

User.where(id: @posts.pluck('distinct author_id'))

Will apply 'DISTINCT' in SQL query (not as Array#uniq)

Note:

If you are trying to get users activerecord relation, 'Distinct' is useless because 'ID' is already unique in users table and you won't get any duplicated user.

But if you need only array of unique author_ids you can use @posts.map(&:author_id).uniq

like image 139
Moamen Naanou Avatar answered Oct 21 '25 23:10

Moamen Naanou



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!