2015-08-25 16 views
4

至於現在我正在研究一個博客應用程序,它通過has_many/belongs_to關聯連接了文章/評論模型。要創建嵌套註釋功能,我使用祖先寶石。不過,我想急切地加載評論的所有後代。有沒有關於如何解決這個問題的想法? 我嘗試使用加入其中但似乎他們產生n + 1查詢。 以下是我如何調用方法在視圖中顯示它們。如何使用Rails和Ancestry在模型後代上執行熱切加載

<%= nested_comments_display comments.arrange(:order => :created_at) %> 

這裏是nested_comments_display方法

def nested_comments_display(comments) 
    comments.map do |comment, sub_comments| 
    render(comment) + content_tag(:div,nested_comments_display(sub_comments), 
           :class => "nested_comment") 
    end.join.html_safe 
end 

我也用decent_exposure寶石和我CommentsController看起來像這樣

class CommentsController < ApplicationController 

    expose(:article) 
    expose(:comments, ancestor: :article) 
    expose(:comment, attributes: :comment_params) 

    .... 
end 

回答

2

解決這個最簡單的方法(即我所知道的)將創建一個對象,該對象保存預加載的整個子樹集合,然後僅從該內存對象中請求子項...

class CachedAncestryCollection 
    def initialize(collection) 
    @collection = collection.to_a 
    end 

    def children_for(parent_id = nil) 
    @collection.select do |node| 
    parent_id ? (node.ancestry && node.ancestry.match(/#{parent_id}$/)) : node.ancestry.nil? 
    end 
    end 
end 

# ... 

preloaded_subtree = Comment.where(:id => comments.map(&:subtree_ids)) 
cached = CachedAncestryCollection.new(preloaded_subtree) 

def nested_comments_display(cached, parent_id = nil) 
    content_tag(:div) do 
    cached.children_for(parent_id).map do |child| 
     nested_comments_display(cached, child.id) 
    end 
    end 
end 
相關問題