2012-04-18 46 views
0

我試圖在查詢我的Activity表時急於加載CommentRails的ActiveRecord:如何通過兩個多態關聯熱切加載對象

# Activity (basic FB-style news feed) 
# user_id 
# primary_source_id (polymorphic object, like "Post", that can have comments) 
# primary_source_type 

# Comment (acts as commentable w/ threading gem) 
# user_id 
# commentable_id 
# commentable_type 

# WHAT GOES HERE?! 
# How do I eager-load comments? 
activities = Activity.includes(???).joins(???) 

# Display code 
activities.each do |activity| 
    render ... # render activity 
    activity.root_comments.each do |comment| 
    render ... # render activity's comments 
    end 
end 

見,我通過Activity小號循環,抓住每一個primary_source(如Post)及其Comment的render我的網頁。目前primary_source正在加載,但是Comment不是;每個循環都會碰到Comment表。這對我來說是一個巨大的表現,它與我所展示的Activity的數量呈線性關係。

我該如何急於加​​載我的Comment

回答

3

假設所有primary_sources都commentable,

activities = Activity.includes(:user, :primary_source => :comment_threads).where... 

...爲我工作。爲了避免碰到數據庫(並且破壞了包含的目的),你必須用comment_threads(包括子註釋)替換對root_comments的所有引用。這是因爲root_comments在寶石(LIB/acts_as_commentable_with_threading.rb)實際上定義爲一個輔助方法:

def root_comments 
    self.comment_threads.where(:parent_id => nil) 
end 

來源:對嵌套協會的Rails Guide部,與所述寶石acts_as_commentable_with_threading和少許試驗和內沿偷看錯誤在控制檯:)

+0

這導致我正確的事情,我看起來像這樣:'Pin.includes(comment_threads:[:children])。find(params [:id])' – 2016-07-14 16:50:52

相關問題