Rails 预加载所有查找结果

发布于 2024-08-17 15:06:55 字数 713 浏览 3 评论 0原文

好吧,我一直在玩一些急切加载的东西,并且有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

格子衫的從容 2024-08-24 15:06:55

我一直在使用 default_scope 在我总是想要急切加载的选定模型上执行此操作:

class Post < ActiveRecord::Base
  has_many :comments
  default_scope :include => :comments, :order => ["title ASC"]
  ...
end

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
ゃ懵逼小萝莉 2024-08-24 15:06:55

您应该能够使用命名范围来执行此操作,但我知道这可能存在许多错误,希望它们现在都已修复。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文