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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With