3

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

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)
4

2 回答 2

6

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

@user.favorites

查看有关 Eager Loading 的截屏视频

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

这将是

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

或 Rails 3.x

 User.includes(:favorites)
于 2011-03-27T20:52:57.037 回答
1

您可以添加: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

于 2011-03-27T20:59:00.607 回答