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 alwa开发者_如何学编程ys want the chapters eager loaded without needing to remember the :include =>
parameter.
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
精彩评论