Nested comments from scratch

后端 未结 9 1257
生来不讨喜
生来不讨喜 2020-12-25 09:03

Let\'s say I have a comment model:

class Comment < ActiveRecord::Base
    has_many :replies, class: \"Comment\", foreign_key: \"reply_id\"
end
         


        
9条回答
  •  自闭症患者
    2020-12-25 09:27

    It seems like what you have is one short step away from what you want. You just need to use recursion to call the same code for each reply as you're calling for the original comments. E.g.

    
    
    <%= render partial: "comment", collection: @comments %>

    <%= comment.content %>

    <%= render partial: "comment", collection: comment.replies %>

    NB: this isn't the most efficient way of doing things. Each time you call comment.replies active record will run another database query. There's definitely room for improvement but that's the basic idea anyway.

提交回复
热议问题