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