user3927582
user3927582

Reputation: 189

Rails ActiveRecord retrieving associated data with two has_many associations

Let's say you have a Licence model that has_many: :seats and the Seat model has_many: :customers.

What I want to get back is an ActiveRecord object of all the customers on a Licence. Is there a way to do this?

I have a solution licence.seats.includes(:customers).flat_map(&:customers) but this will return an Array object which is not what I am looking for.

Thanks for your help!

Upvotes: 0

Views: 221

Answers (3)

Anand
Anand

Reputation: 6531

Instead of using joins/includes this can be efficient for large records.

class Licence
    has_many :seats

    def customers
      #customer belongs_to seat
      Customer.where(seat_id: seats.pluck(:id))
    end
end

Query -

licence.customers

Upvotes: 0

lei liu
lei liu

Reputation: 2775

Use has_many through option:

class Licence
    has_many :seats
    has_many :customers, through: :seats
end

Now you can get customers by

licence.customers

Upvotes: 6

Marek Lipka
Marek Lipka

Reputation: 51151

joins does the job:

Customer.joins(:seat).where(seats: { licence_id: licence.id })

It returns Relation, just as you want.

Upvotes: 1

Related Questions