开发者

Always eager load association with entity

开发者 https://www.devze.com 2023-02-05 15:39 出处:网络
Is it possible to always eager load an association when an entity is loaded. For example class Book has_many :chapters

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
0

精彩评论

暂无评论...
验证码 换一张
取 消