Rails嵌套评论:如何向表单传递父评论ID?
嵌套评论表单的父ID传递解决方案
1. 修改评论表单局部模板
将app/views/comments/_comment_form.html.erb调整为以下代码,通过局部变量parent动态绑定父评论ID,并用隐藏字段传递该值:
<%# 构建关联文章的评论对象,同时绑定父评论(若存在) %> <% comment = article.comments.build(parent: parent) %> <%= form_with(model: [article, comment]) do |f| %> <p>Comment:</p> <%= f.text_area :body, class:'' %> <%# 自动传递parent_id,无父评论时会设为nil %> <%= f.hidden_field :parent_id %> <%= image_submit_tag("Post.jpg", height: "25", width: "25", class: "mt-5 ms-3") %> <% end %>
2. 优化CommentsController的create方法
简化控制器逻辑,利用关联自动绑定用户和文章,确保parent_id能被正确接收:
class CommentsController < ApplicationController before_action :authenticate_user! def create # 通过current_user直接关联评论者,无需手动赋值 @comment = current_user.comments.new(comment_params) @comment.save redirect_to article_path(@comment.article_id) end private def comment_params # 移除user_id,由current_user自动关联;保留article_id和parent_id params.require(:comment).permit(:body, :article_id, :parent_id) end end
3. 确认嵌套路由配置
确保路由中包含文章与评论的嵌套关系,保证表单提交路径自动携带article_id:
# config/routes.rb resources :articles do resources :comments end
逻辑说明
- 从文章页面调用表单时(
parent: nil),隐藏字段parent_id会自动设为空,满足顶级评论需求; - 回复评论时(
parent: comment),隐藏字段会自动填充目标评论的ID,提交后控制器可直接获取该值; - 利用Rails关联特性,通过
current_user.comments.new自动绑定评论者,避免手动赋值的冗余操作。
内容的提问来源于stack exchange,提问作者German
相关产品推荐
相关产品推荐

