在Rails中防止N + 1查询 [英] Preventing N+1 queries in Rails
问题描述
我已经看到了一些示例,这些示例在调用ActiveRecord的 find
方法之一时传递:include
哈希值的例子在Rails中。但是,我还没有任何有关通过关系方法是否可行的示例。例如,假设我有以下内容:
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)
推荐答案
您不能将关系用作Class方法。它是实例方法。您可以致电
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
将会
User.find(:all, :include => :favorites)
或for Rails 3.x
or for Rails 3.x
User.includes(:favorites)
这篇关于在Rails中防止N + 1查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!