简体   繁体   English

防止Rails中的N + 1个查询

[英]Preventing N+1 queries in Rails

I've seen a few examples of passing an :include hash value when calling one of ActiveRecord's find methods in Rails. 我已经看到了一些在Rails中调用ActiveRecord的find方法时传递一个:include哈希值的例子。 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)

You can't use relations as Class methods. 您不能将关系用作Class方法。 It is instance methods. 它是实例方法。 You can call 你可以打电话

@user.favorites

Check out this screencast about Eager Loading 看看这个关于Eager Loading的截屏视频

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

It will be 这将是

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

or for Rails 3.x 或者对于Rails 3.x.

 User.includes(:favorites)

You can add :include to your model's associations to eager load the second-order associations when the object is loaded. 您可以添加: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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM