Home > Enterprise >  Rails Eager loading not loading nested associative records though included
Rails Eager loading not loading nested associative records though included

Time:06-28

I have three classes as follows

Class User < ActiveRecord

    has_many :addresses

end

Class Address < ActiveRecord

    belongs_to :country

end

Class Country < ActiveRecord

    has_many :addresses
end

I am trying to eager load all the nested associative records by the following command

User.includes(addresses: :country) But with this on rails console, only User and addresses get loaded but not the country. I am not sure what I am missing.

CodePudding user response:

You need to use a hash to declare eager loading of nested resources, e.g.

User.includes(addresses: [:country])

instead of

User.includes(addresses: :country)

See the docs

Here's a full working example (Rails 6)

class Person < ApplicationRecord
  has_many :projects
end

class Company
  has_many :projects
end

class Project < ApplicationRecord
  belongs_to :person
  belongs_to :company
end

Then, on the console:

ActiveRecord::Base.logger = Logger.new(STDOUT)
me = Person.includes(projects: [:company]).find 4
Person Load (0.3ms)  SELECT "people".* FROM "people" WHERE "people"."id" = $1 LIMIT $2  [["id", 4], ["LIMIT", 1]]
Project Load (0.4ms)  SELECT "projects".* FROM "projects" WHERE "projects"."person_id" = $1  [["person_id", 4]]
Company Load (0.5ms)  SELECT "companies".* FROM "companies" WHERE "companies"."id" IN ($1, $2, $3, $4, $5 ...)
me.projects.first.company.name
=> "my first project's customer name"

Note that there is no query to the database between asking for the name of the customer of my first project and the production of the return value. If there would have been one, the query would have been printed by the logger that pipes it output to STDOUT.

  • Related