Ruby on Rails
EagerLoadingOfAssociations

See the section titled “Eager loading of associations” in the ActiveRecord::Associations API docs.


Suppose you have four models: one grandfather, ‘author’, one father ‘book’ and two childs, ‘comment’ and ‘sample_chapter’:


class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
  has_many :sample_chapters
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :book
end

class SampleChapter < ActiveRecord::Base
  belongs_to :book
end

If you want to find a author for a given :id with all descendants (books, comments and sample chapters), you can use eager loading (parameter :include):


@everything_about_an_author = Author.find(:id, :include => [:books => [:comments, :sample_chapters]]

Pay attention in using arrays (‘[]’), not hashes (’{}’) to include descendants.

Now you can ‘walk’ on an author, his books, sample chapters and comments, with just one hit on database:


@everything_about_an_author.books.each do |b|
  b.comments.each do |c|
  
  end
  b.sample_chapters.each do |sc|
  
  end
end