gpt4 book ai didi

ruby-on-rails - 使用 gem 'closure_tree' 在 Rails 4 中嵌套注释

转载 作者:数据小太阳 更新时间:2023-10-29 08:46:47 24 4
gpt4 key购买 nike

使用 gem 'closure_tree' 在 Rails 4 中嵌套注释

鉴于评论是文章的嵌套资源,我如何重构站点教程中的以下代码以创建嵌套评论?

特别是,我如何整合这两行:

@comment = parent.children.build(comment_params)

@comment = @article.comments.create(comment_params)

http://guides.rubyonrails.org/getting_started.html

路线.rb

resources :articles do
resources :comments
end

评论 Controller .rb

class CommentsController < ApplicationController
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(comment_params)
redirect_to article_path(@article)
end


private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end

http://www.sitepoint.com/nested-comments-rails/

评论 Controller .rb

class CommentsController < ApplicationController
def create
if params[:comment][:parent_id].to_i > 0
parent = Comment.find_by_id(params[:comment].delete(:parent_id))
@comment = parent.children.build(comment_params)
else
@comment = Comment.new(comment_params)
end
end


private
def comment_params
params.require(:comment).permit(:body)
end
end

最佳答案

这不是你想要的答案,但对你有帮助


嵌套

enter image description here

我们使用 ancestry gem 实现了真正的“嵌套”评论显示(刚刚查看了 closure_tree - 非常好,将进一步研究)。

我称之为“真正的”嵌套,因为如果您希望嵌套发生在回复 以及标准化评论中,您必须做一些特别的事情。您必须执行 recursive loop ,包括你需要的所有嵌套评论

要做到这一点,您需要三件事:

  1. Hierarchy in your model
  2. Ability to access hierarchies correctly (children / parents etc)
  3. Recursive view to display them all

这是我们的做法:


层次结构

模型中的层次结构是第一步,也是最重要的一步。您的 closure_tree 示例似乎很好地证明了这一点。我们使用了 ancestry —— 似乎它们都以不同的方式实现了相同的结果:

enter image description here

正如您从数据中看到的那样,您将能够看到存储数据的层次结构使您能够正确调用它们(这对于显示它们至关重要)。 Ancestry 使用以下格式表示结构:parent_1/parent_2 - 我相信 closure_tree 的做法有所不同

--

访问

正确设置数据库后,您必须确定对数据的访问权限。

我们使用 Ancestry's children method :

enter image description here

这允许我们循环访问对象,然后我们可以从中调用 children 方法:

--

递归循环

最后,您将能够将所有这些与您的 View 联系在一起:

#app/views/comments/index.html.erb
<%= render partial: "comment", locals: { collection: @comments } %>

#app/views/comments/_comment.html.erb
<% collection.arrange.each do |comment, sub_item| %>
<li>
<%= link_to comment.title, your_path(comment) %>
<%= render partial: "category", locals: { collection: category.children } if category.has_children? %>
</li>
<% end %>

这个简单的 partial 将为您提供创建真正嵌套的注释结构所需的递归。当然,这将取决于您的 closure_tree gem,但无论如何都会给您一些不错的想法!

关于ruby-on-rails - 使用 gem 'closure_tree' 在 Rails 4 中嵌套注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676769/

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