Rails 5.2 中的空 Post

Empty Post in Rails 5.2

我正在尝试在 Advertisement 视图中添加 Comment 模型的助手 _form。我在路线 /advertisement/:id

中调用助手 <%= render 'comments/form', comment: @comment %>

这是我的 评论 _form :

<%= form_with(model: comment, local: true,  url: "/comments") do |form| %>
  <% if comment &&  comment.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(comment.errors.count, "error") %> prohibited this comment from being saved:</h2>

      <ul>
      <% comment.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-group">
    <%= form.label :content %>
    <%= form.text_area :content, class:"form-field" %>
  </div>

  <%= form.hidden_field :advertisment_id, value:params[:id]  %>

  <div class="actions">
    <%= form.submit "Envoyer", class:"btn btn-primary", url: 'comments' %>
  </div>
<% end %>

我指定 url: "/comments" 因为我在 /advertisment/:id 并且默认情况下操作针对此处。

但是当post到达我的评论控制器时,它无法读取参数。

ActionController::ParameterMissing in CommentsController#create

奇怪的是我可以访问参数:

{"utf8"=>"✓", "authenticity_token"=>"0+swOqHPEHN2Gwh0TO3iC7VPRz4ROLoBlkaMkOdnjjYxWHoDer7AwrgnQpu+9VHfSY90yMSRsNp8ojvPJxuzmQ==", "content"=>"Test", "advertisment_id"=>"1", "commit"=>"Envoyer"}

所以这里是 评论控制器:

class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :edit, :update, :destroy]

  # [...]

  # POST /comments
  # POST /comments.json
  def create
    @comment = Comment.new(comment_params.merge(:user_id => @session_user.id))

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  # [...]

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:content, :advertisment_id)
    end
end

非常感谢您的帮助

根据文档 here,如果您在 form_with 中指定 url 选项而没有 scope 选项,收到的参数将丢失 prefixes在那里的名字。因此

params.require(:comment).permit(:content, :advertisment_id)

将引发错误,因为参数不包括 comment

您应该删除 form_with 中的 url 选项或同时使用 urlscope 选项。

这可能是因为您的 @commentnil,所以 form_with 就像旧的 form_tag 助手一样工作。

通过使用 form_with,像 <%= form.text_field :content %>

这样的字段
  • 如果您的模型被展示,它将生成<input type="text" name="comment[content]" />
  • 如果您的模型没有出现,它将生成<input type="text" name="content" />

在第二种情况下,您的强参数检查将拒绝裸参数

为了能够解决它,只需为您的render

分配一个有效的模型
<%= render 'comments/form', comment: Comment.new %>