从头开始嵌套评论 [英] Nested comments from scratch

查看:66
本文介绍了从头开始嵌套评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个评论模型:

class 注释 

我可以在这样的视图中显示评论实例的回复:

comment.reply 做 |reply|回复内容结尾

但是,如何遍历回复的回复?它的回复?以及它的回复广告?我觉得我们需要通过类方法制作一个回复的多维数组,然后在视图中循环遍历这个数组.

我不想用gem,我想学习

解决方案

似乎你所拥有的离你想要的只有一步之遥.您只需要使用递归为每个回复调用与调用原始评论相同的代码.例如

<div id="评论"><%= 渲染部分:评论",集合:@comments %>

<!-- _comment 部分 --><div class="comment"><p><%= comment.content %></p><%= 渲染部分:评论",集合:comment.replys %>

注意:这不是最有效的做事方式.每次调用 comment.replys 活动记录时,都会运行另一个数据库查询.肯定有改进的余地,但无论如何这是基本的想法.

Let's say I have a comment model:

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

I can show a comment instance`s replies in a view like so:

comment.replies do |reply|
   reply.content
end

However, how do I loop through the replies of the reply? And its reply? And its reply ad infitum? I'm feeling we need to make a multidimensional array of the replies via class method and then loop through this array in the view.

I don't want to use a gem, I want to learn

解决方案

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.

<!-- view -->
<div id="comments">
  <%= render partial: "comment", collection: @comments %>
</div>

<!-- _comment partial -->
<div class="comment">
  <p><%= comment.content %></p>
  <%= render partial: "comment", collection: comment.replies %>
</div>

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.

这篇关于从头开始嵌套评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆