Rails渴望在所有发现中加载 [英] Rails Eager Loading on All Finds
问题描述
好的,我一直在处理一些急切的加载工作,并且有2种模型,例如:
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
和
Class Cookbook < ActiveRecord::Base
has_many :recipes, :include => [:recipetags]
end
当我找到一本食谱时,效果很好然后我急于加载食谱,然后急于加载:recipetags:
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)
,并且在这种情况下也希望加载:recipetags。
and have it eager load the :recipetags in that case as well.
我意识到这似乎是微不足道的,但是实际上我在Recipe上有大约4-5个关联,我只是不在这里显示它们,而不必显式地在每个上执行:include找到电话,我希望它能发生。我假设我可以重写Recipe.find以在Recipe模型中做到这一点,但想知道是否有更清洁的方法。...
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....
推荐答案
我一直在使用default_scope在希望始终加载的选定模型上执行此操作:
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
这篇关于Rails渴望在所有发现中加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!