Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always eager load association with entity

Is it possible to always eager load an association when an entity is loaded. For example

class Book
  has_many :chapters
end

class Chapters
  belongs_to :book
end

book = Book.find_by_title('Moby Dick')

I know that you can eager load in the call to find ie. book = Book.find_by_title( 'Moby Dick', :include => :chapters) but in this case I know that any time I find a book I always want the chapters eager loaded without needing to remember the :include => parameter.

like image 340
Paul Alexander Avatar asked Jan 19 '11 02:01

Paul Alexander


People also ask

What is eager load?

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by the use of the Include method. It means that requesting related data be returned along with query results from the database.

How does eager loading work in Rails?

Eager loading lets you preload the associated data (authors) for all the posts from the database, improves the overall performance by reducing the number of queries, and provides you with the data that you want to display in your views, but the only catch here is which one to use.


1 Answers

You can include a "default_scope" in your model.

For Rails 4:

class Book
  has_many :chapters
  default_scope { includes(:chapters) }
end

For Rails 3:

class Book
  has_many :chapters
  default_scope includes(:chapters)
end

For Rails 2:

class Book
  has_many :chapters
  default_scope :include => :chapters
end
like image 184
Dylan Markow Avatar answered Oct 26 '22 01:10

Dylan Markow