“父必须存在”和“未找到用于CommentController#create的模板,渲染头:no_content” Rails 5

时间:2019-03-26 20:05:35

标签: ruby-on-rails ruby

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

首先,当我提交评论时-我会弹出一个对话框来保存文件(没有要保存的文件)。

chrome popup 但是,注释并未创建,因为我的应用程序认为该注释的属性之一必须存在,而不必这样做。

这是我提交时的错误:

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

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

comments_controller.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

schema.rb

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

comment.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 %>

1 个答案:

答案 0 :(得分:1)

默认情况下,Rails 5使belongs_to关联成为必要-有一篇很棒的文章here

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

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