Blankman
Blankman

Reputation: 266988

How to do eager loading when association is 2 levels deep?

Say my models are like:

class Book < ActiveRecord::Base
  has_many :chapters
end

class Chapter < ActiveRecord::Base
  belongs_to :book
  has_many :pages
end

class Pages < ActiveRecord::Base
  belongs_to :chapter
end

I am currently doing this:

book = Book.find(1)

book.chapters.each do |chapter|
end

But now I need access to the chapter.pages inside of the loop, so I want to eager load all the pages for each chapter.

I know I can do this for chapters:

book = Book.includes(:chapters).find(1)

But how to eager load the pages?

Upvotes: 0

Views: 58

Answers (1)

codyeatworld
codyeatworld

Reputation: 1283

You can pass an array to the name of the association:

Book.includes(chapters: [:pages])

Upvotes: 1

Related Questions