I have a show
method that must render objects json
of three models that are related to each other by their id
.
The models are the following:
class Company < ApplicationRecord
has_many :areas
end
class Area < ApplicationRecord
belongs_to :company
has_many :area_contacts
end
class AreaContact < ApplicationRecord
belongs_to :area
end
Where company has a company_id and is related through this field to the area model, and area_contact is related to the area model through the field area_id.
My show
method in the _companies_controller.rb_ file is defined as follows:
def show
@areas = @company.areas
@area_contacts = AreaContact.includes(:area).find_by_area_id(@areas.ids)
render json: { company: @company,
areas: @areas,
area_contacts: @area_contacts
}
end
The problem is that it only brings me the first area_contact
, no matter how many are related to area_id
that the query is brought when I call the company. That is, if I consult the company_id = 1
, it will bring me all the areas
that have company_id = 1
, and in turn should bring me all area_contact
related to area_id
that the query was brought by the company_id = 1
, but It only brings me first.
So I think the problem is defined in this part of my code:
@area_contacts = AreaContact.includes(:area).find_by_area_id(@areas.ids)
Please, I appreciate any help or comment.