Reputation: 382
I have 3 models as the following
class House < ApplicationRecord
has_many :ownerships
has_many :people, through: :ownerships
end
class Person < ApplicationRecord
has_many :ownerships
has_many :houses, through: :ownerships
end
and
class Ownership < ApplicationRecord
belongs_to :house
belongs_to :person
end
Basically, I'd like to make a query as JSON to get a list of all houses
with associated people
. The point is some houses don't have any people and some people don't own a house so the Ownership
association doesn't have all the houses' ids. If a house doesn't belong to any person so the response should be nil.
The result from the query is, for example, the following:
{
house1: {
owners: [
person1,
person2
]
},
house2: {
owners: null
},
house3: {
owners: [
person2
]
}
}
I tried to use includes
but I got separated arrays of items without the associated structure.
House.all.includes(:people).as_json(include: [:people])
but people
value is in a separated key and not associated with the houses
.
Upvotes: 0
Views: 57
Reputation: 6253
for query you can as below
House.includes(ownerships: :person).as_json(include: [:people])
this will return house with your expected result. inside your includes, you type the relations between house -> ownerships (plural) then from ownership -> person (singular since ownership belong to)
Upvotes: 2