3

我在Rails中调用ActiveRecord的find方法中的一个时发现了一些传递:include散列值的例子。但是,我还没有看到任何关于这是否可以通过关系方法的例子。举例来说,假设我有以下几点:我在Rails中防止N + 1查询

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) 
+1

这些天,用[子弹](https://github.com/ flyerhzm /子弹)。 – Barry 2015-02-12 15:45:16

回答

6

不能使用关系作为类方法。它是实例方法。您可以拨打

@user.favorites 

看看这个截屏约预先加载

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

这将是

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

或为Rails 3.X

User.includes(:favorites) 
+0

这并没有回答我是否可以使用关系方法而不是'find'方法的问题。 – 2011-03-27 20:59:10

+1

答案是'你不能' – fl00r 2011-03-27 21:00:08

+0

这太糟糕了,善良的一些击败Rails的简单。谢谢(你的)信息。 – 2011-03-27 21:18:00