gpt4 book ai didi

ruby-on-rails - 防止 Rails 中的 N+1 查询

转载 作者:行者123 更新时间:2023-12-04 03:46:53 26 4
gpt4 key购买 nike

我见过几个在 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)

最佳答案

您不能将关系用作类方法。它是实例方法。你可以打电话

@user.favorites

查看有关预加载的截屏视频

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

会是

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

或者对于 Rails 3.x

 User.includes(:favorites)

关于ruby-on-rails - 防止 Rails 中的 N+1 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5452340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com