Reputation: 189
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
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
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
Reputation: 51151
joins
does the job:
Customer.joins(:seat).where(seats: { licence_id: licence.id })
It returns Relation
, just as you want.
Upvotes: 1