3

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!

Shelby S
  • 400
  • 4
  • 17
  • 1
    If you're just fetching a single company and want to load it's locations, you don't need to use `includes`. Doing @company = Company.find(params[:id])` followed by `@company.locations` will perform just as many queries as `@company = Company.includes(:locations).find(params[:id])` – Bart Jedrocha Jul 27 '16 at 19:40

3 Answers3

3

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

Fakhir Shad
  • 1,071
  • 8
  • 20
2

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

Greg Answer
  • 717
  • 5
  • 15
1

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 :)

Sam Henderson
  • 479
  • 5
  • 7