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