Rails 预加载所有查找结果
好吧,我一直在玩一些急切加载的东西,并且有 2 个模型,例如:
Class Recipe < ActiveRecord::Base
belongs_to :cookbook
has_many :recipetags
end
哪个
Class Cookbook < ActiveRecord::Base
has_many :recipes, :include => [:recipetags]
end
模型效果很好,当我找到一本食谱时,我急切加载菜谱,然后急切加载菜谱:recipetags:
cb = Cookbook.find(10590, :include => [:recipes])
但我还想做的是,每当我打开一个菜谱时,让它自动拉入所有急切的关联 - 基本上我想做的是:
rec = Recipe.find(123)
并在这种情况下让它急切地加载 :recipetags。
我意识到这似乎微不足道,但实际上我在 Recipe 上有大约 4-5 个关联,我只是不在这里显示它们,而不是必须在每个查找调用上显式执行 :include 我希望它发生。我假设我可以覆盖 Recipe.find 以在 Recipe 模型中执行此操作,但想知道是否有更干净的方法......
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....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我一直在使用 default_scope 在我总是想要急切加载的选定模型上执行此操作:
I've been using default_scope to do it on selected models where I always want to eager load:
您应该能够使用命名范围来执行此操作,但我知道这可能存在许多错误,希望它们现在都已修复。
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.