Nested comments from scratch

后端 未结 9 1277
生来不讨喜
生来不讨喜 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:40

    This will be my approach:

    • I have a Comment Model and a Reply model.
    • Comment has_many association with Reply
    • Reply has belongs_to association with Comment
    • Reply has self referential HABTM

      class Reply < ActiveRecord::Base
        belongs_to :comment
        has_and_belongs_to_many :sub_replies,
                        class_name: 'Reply',
                        join_table: :replies_sub_replies,
                        foreign_key: :reply_id,
                        association_foreign_key: :sub_reply_id
      
        def all_replies(reply = self,all_replies = [])
          sub_replies = reply.sub_replies
          all_replies << sub_replies
          return if sub_replies.count == 0
          sub_replies.each do |sr|
            if sr.sub_replies.count > 0
              all_replies(sr,all_replies)
            end
          end
          return all_replies
        end
      
      end 
      

      Now to get a reply from a comment etc:

    • Getting all replies from a comment: @comment.replies
    • Getting the Comment from any reply: @reply.comment
    • Getting the intermediate level of replies from a reply: @reply.sub_replies
    • Getting all levels of replies from a reply: @reply.all_replies

提交回复
热议问题