[英]Preventing N+1 queries in Rails
我已經看到了一些在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)
您不能將關系用作Class方法。 它是實例方法。 你可以打電話
@user.favorites
看看這個關於Eager Loading的截屏視頻
http://railscasts.com/episodes/22-eager-loading
這將是
User.find(:all, :include => :favorites)
或者對於Rails 3.x.
User.includes(:favorites)
您可以添加: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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.