gpt4 book ai didi

ruby-on-rails - 从头开始嵌套评论

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:21 26 4
gpt4 key购买 nike

假设我有一个评论模型:

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

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

comment.replies do |reply|
reply.content
end

但是,我如何循环遍历回复的回复?它的答复是什么?它的回复广告infitum?我觉得我们需要通过类方法创建一个回复的多维数组,然后在 View 中循环遍历该数组。

我不想用 gem ,我想学习

最佳答案

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

<!-- 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>

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

关于ruby-on-rails - 从头开始嵌套评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22635981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com