防止 Rails 中的 N+1 查询
我见过一些在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能将关系用作类方法。它是实例方法。您可以观看
有关预加载的截屏视频
http://railscasts.com/episodes/22-eager -loading
它将是
或 对于 Rails 3.x
You can't use relations as Class methods. It is instance methods. You can call
Check out this screencast about Eager Loading
http://railscasts.com/episodes/22-eager-loading
It will be
or for Rails 3.x
您可以将
: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