将parent_id传递给评论

在我的应用程序中,我有post有评论。 现在我还想为这些评论添加评论(嵌套评论)。

我目前这样做,但它不会将我的parent_id写入数据库:

我的_comment.html.erb部分中的评论链接:

 

我的评论/ new.html.erb:

      

我的comments_controller.rb:

  def new @post=Post.find(params[:post_id]) @comment = Comment.new(parent_id: params[:parent_id]) end def create @post = Post.find(params[:post_id]) @comment=@post.comments.build(comment_params) @comment.user=current_user if @comment.save redirect_to :back end private def comment_params params.require(:comment).permit(:body, :parent_id) end 

执行的查询:

 INSERT INTO "comments" ("body", "created_at", "post_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" 

祖先

我打算告诉你如何根据需要分配parent_id ,但考虑到我们之前创建了一个评论系统 ,我觉得最好给你一些系统的想法; 而不是具体细节

我们使用一个名为Ancestry的gem来让我们能够嵌套我们的对象:

在此处输入图像描述

这使我们可以灵活地创建更强大的嵌套结构(我将在一分钟内详述):

 #config/routes.rb resources :posts do resources :comments, only: [:new, :create] do get :reply #-> domain.com/posts/:post_id/comments/:id/reply end end #app/controllers/comments_controller.rb Class CommentsController < ApplicationController def new @post = Post.find params[:post_id] @comment = Comment.new end def reply @post = Post.find params[:post_id] @comment = Comment.new @parent = params[:id] render :new end def create @post = Post.find params[:post_id] @comment = @post.comments.new comment_params @comment.save end private def comment_params params.require(:comment).permit(:body, :ancestry) end end #app/views/comments/new.html.erb <%= form_for [@post, @comment] do |f| %> <%= f.text_field :body %> <%= f.hidden_field :ancestry, value: @parent if @parent.present? %> <%= f.submit %> <% end %> 

使用ancestry的美妙(我推荐的真正原因)是能够创建一个真正的嵌套视图:

在此处输入图像描述

为此,您可以使用我们创建的部分:

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

    落下

    在此处输入图像描述

     #app/helpers/application_helper.rb def nested_dropdown(items) result = [] items.map do |item, sub_items| result << [('- ' * item.depth) + item.name, item.id] result += nested_dropdown(sub_items) unless sub_items.blank? end result end #app/views/posts/new.html.erb <%= form_for @post do |f| %> <%= f.select(:category_ids, nested_dropdown(Category.all.arrange), prompt: "Category", selected: @category ) %> <% end %> 

    按以下方式填写评论表:

     <%= form_for @comment do |f| %> <%= f.hidden_field :parent_id, @post.id %> <%= f.text_area :body %> <%= f.submit %> <% end %>