防止 Rails 中的 N+1 查询

发布于 2024-10-27 00:39:19 字数 681 浏览 9 评论 0原文

我见过一些在 Rails 中调用 ActiveRecord 的 find 方法之一时传递 :include 哈希值的示例。然而,我还没有看到任何例子来说明这是否可以通过关系方法实现。例如,假设我有以下内容:

def User < ActiveRecord::Base
  has_many :user_favorites
  has_many :favorites, :through => :user_favorites
end

def Favorite < ActiveRecord::Base
  has_many :user_favorites
  has_many :users, :through => :user_favorites
end

def UserFavorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :favorite
end

我看到的所有示例都显示如下代码:

User.find(:all, :include => :favorite)

但我没有看到任何显示关系使用的示例。我可以做这样的事情吗?

User.favorites(:include => :user)

I've seen a few examples of passing an :include hash value when calling one of ActiveRecord's find methods in Rails. However, I haven't seen any examples of whether this is possible via relationship methods. For example, let's say I have the following:

def User < ActiveRecord::Base
  has_many :user_favorites
  has_many :favorites, :through => :user_favorites
end

def Favorite < ActiveRecord::Base
  has_many :user_favorites
  has_many :users, :through => :user_favorites
end

def UserFavorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :favorite
end

All the examples I see show code like this:

User.find(:all, :include => :favorite)

But I don't see any examples showing the use of relationships. Would it instead be possible for me to do something like this?

User.favorites(:include => :user)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

梦在夏天 2024-11-03 00:39:19

您不能将关系用作类方法。它是实例方法。您可以观看

@user.favorites

有关预加载的截屏视频

http://railscasts.com/episodes/22-eager -loading

它将是

 User.find(:all, :include => :favorites)

或 对于 Rails 3.x

 User.includes(:favorites)

You can't use relations as Class methods. It is instance methods. You can call

@user.favorites

Check out this screencast about Eager Loading

http://railscasts.com/episodes/22-eager-loading

It will be

 User.find(:all, :include => :favorites)

or for Rails 3.x

 User.includes(:favorites)
带刺的爱情 2024-11-03 00:39:19

您可以将 :include 添加到模型的关联中,以便在加载对象时立即加载二阶关联。

http://api.rubyonrails.org/classes/ActiveRecord /Associations/ClassMethods.html#method-i-belongs_to
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

You can add :include to your model's associations to eager load the second-order associations when the object is loaded.

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

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