Rails Eager Loading on All Finds

那年仲夏 提交于 2019-11-27 10:34:53

问题


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....


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2042507/rails-eager-loading-on-all-finds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!