OK, I've been playing around with some of the eager loading things, and have 2 models something like:
Class Recipe < ActiveRecord::Base
belongs_to :cookbook
has_many :recipetags
end
and
Class Cookbook < ActiveRecord::Base
has_many :recipes, :include => [:recipetags]
end
Which is working out well, when I find a Cookbook, then I eager load the recipes, and in turn the recipes eager load the :recipetags:
cb = Cookbook.find(10590, :include => [:recipes])
But what I want to also do is whenever I open a recipe, have it pull in all of it's eager associations automatically - basically I want to do:
rec = Recipe.find(123)
and have it eager load the :recipetags in that case as well.
I realize this seems trivial, but in actuality I开发者_如何学运维 have about 4-5 associations on Recipe, I'm just not showing them here, and rather than having to explicitly do the :include on every find call I'd like it to just happen. I'm assuming I can override Recipe.find to do it in the Recipe model, but was wondering if there was a cleaner way....
I've been using default_scope to do it on selected models where I always want to eager load:
class Post < ActiveRecord::Base
has_many :comments
default_scope :include => :comments, :order => ["title ASC"]
...
end
You should be able to do this with named scopes, but I understand that there were a number of possible bugs with that, hopefully they are all fixed now.
精彩评论