Steven Jeffries
Steven Jeffries

Reputation: 3582

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?

Upvotes: 4

Views: 3775

Answers (1)

Moamen Naanou
Moamen Naanou

Reputation: 1713

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

Upvotes: 4

Related Questions