almo
almo

Reputation: 6367

Get all unique associations in Rails 5

I have and object rides and ride belongs_to company.

I get a list of rides

@rides = Ride.where(...)

What I need now is to store all companies of those ride in @companies where I want to have every company only once, even if two rides have the same company.

Upvotes: 0

Views: 673

Answers (2)

Laurent
Laurent

Reputation: 104

PostgresQL is very efficient at doing that kind of work, much more so than Ruby.

You could write:

@rides = Ride.includes(:company).where(foo: "bar")

@companies = @rides.distinct.pluck('companies.name')

Which will result in the SQL query:

SELECT DISTINCT companies.name FROM "rides" LEFT OUTER JOIN "companies" ON "companies"."id" = "rides"."company_id" WHERE (rides.foo IS "bar")

Upvotes: 0

Gokul
Gokul

Reputation: 3231

You can get all unique companies of all rides as below:

@rides = Ride.includes(:company).where(...)

@companies = @rides.map(&:company).uniq

Note: includes will load all companies in single query which are associated to resulting rides (prevents N+1 query problem).

Upvotes: 1

Related Questions