首页 > 解决方案 > “父级必须存在”和“没有找到 CommentsController#create 的模板,渲染头:no_content” Rails 5

问题描述

我收到一个“新评论”表单的奇怪错误。

首先,当我提交评论时,我会弹出一个保存文件的弹出窗口(没有要保存的文件)。

铬弹出 但是,评论没有创建,因为我的应用程序认为评论的属性之一必须存在,而它不需要。

这是我提交时的错误:

errors: ["Parent must exist"]
No template found for Events::CommentsController#create, rendering head :no_content

(但是,当您提交带有头像的评论时,它会按预期工作)

评论控制器.rb

  def create
    @comment = @commentable.comments.build(comment_params)
    if @comment.save
      flash[:success] = "Your comment was successfully saved."
      redirect_to @commentable
    else
      puts "errors: #{@comment.errors.full_messages}"
      flash[:danger] = "Uh Oh"
    end
  end

架构.rb

  create_table "comments", force: :cascade do |t|
    t.integer "parent_id"
    t.string "commentable_type"
    t.bigint "commentable_id"
  end

评论.rb

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true

  belongs_to :parent, class_name: "Comment"
  has_many :children, class_name: "Comment", foreign_key: :parent_id, dependent: :destroy
end

new_comment_form.html.erb

<%= form_for [commentable, Comment.new] do |f| %>
  <div class="form-group">
    <div class="col-6">
      <%= f.text_area :body, class: "form-control", placeholder: "", style: "height: 200px;" %>
    </div>
  </div>
  <div class="form-group">
    <div class="col-3">
      <%= f.submit "add comment", class: "btn btn-light ", id: "submit-comment" %>
    </div>
  </div>
<% end %>

标签: ruby-on-railsruby

解决方案


Rails 5默认需要关联 -这里belongs_to有一篇很棒的文章。

基本上,您只需将您的belongs_to关系标记为可选:

belongs_to :parent, class_name: "Comment", optional: true

推荐阅读