I have the following setup: Company has_many :locations Location belongs_to :company
When I call Company.includes(:locations), I'm getting the company returned back, but none of the associated locations.
Any ideas are appreciated!
I have the following setup: Company has_many :locations Location belongs_to :company
When I call Company.includes(:locations), I'm getting the company returned back, but none of the associated locations.
Any ideas are appreciated!
Eager Loading is necessary as it optimizes the performance of your application and prevent your system to run into N+1 query problem. Suppose you have 3000 companies in your database then your database will be flooded with 3000+1 queries. So in the controller you can achieve it as
@companies = Company.includes(:locations)
Similarly for single company you can do it as
@company = Company.includes(:locations).find(params[:id])
Now locations will be eagerly loaded and you can fetch them as
@companies.collect{ |company| company.locations }
OR
@company.locations
Note you can use any iterator. I used 'collect' just for the purpose of elaboration. Thanks
I'm not sure what you are trying to do with a company, but if you want one company and it's locations you would generally do the following:
class Company
has_many :locations
end
class Location
belongs_to :company
end
class CompaniesController < ApplicationController
def show
@company = Company.find(params[:id])
@locations = @company.locations
end
end
Then in your show
view, you would call @locations.each do |location|
in order to iterate over the list of locations
I ran into this problem when trying to send the data from my query back as JSON.
@companies = Company.includes(:locations)
render :json => @companies.to_json( :include => [:locations] )
Worked for me :)