jQuery验证提交表单ActionController :: ParameterMissing

时间:2017-06-11 06:21:13

标签: javascript jquery ruby-on-rails

服务器日志:

`ActionController::ParameterMissing (param is missing or the value is empty: comment)`

使用pry gem gem params:

 <ActionController::Parameters {"utf8"=>"✓", "comment_name"=>"123432",
 "comment_description"=>"231424", "commit"=>"submit", 
"controller"=>"comments", "action"=>"create", "article_id"=>"5"} permitted: false>

我知道:comment应该包装coment_namecomment_description

所以在验证时添加submitHandler尝试修复格式错误

点击浏览器显示的提交按钮:

enter image description here

jquery验证:

$(function () {

    $("form#new_comment").validate({
        rules: {
            comment_name: {
                required: true,
                minlength: 3
            },

            comment_description: {
                required: true,
                minlength: 5
            },
            submitHandler: function (form) {
                $.ajax({
                    url: form.action,
                    type: form.method,
                    data: $(form).serializeArray(),
                    dataType: 'script'
                });
            }
        }
    });
});

_form.html.erb:

<%= simple_form_for [@article, @article.comments.build], remote: true do |f| %>
    <%= f.input :name, input_html: { name: "comment_name"} %>
    <%= f.input :description, input_html: { name: "comment_description" } %>
    <%= f.submit :submit, class: "btn btn-default" %>
<% end %>

comment_controller:

class CommentsController < ApplicationController

  before_action :get_article
  before_action :authenticate_user!

  def create
    @comment = @article.comments.create(comment_params)
    @comment.user_id = current_user.id
    if @comment.save
      respond_to do |format|
        format.html { redirect_to @article, notice: "creaed succeed"}
        format.js { }
      end
    else
      redirect_to @article, notice: "characters is too short or name has been taken"
    end
  end

  def destroy
    @comment = @article.comments.find(params[:id])
    if @comment.destroy
      respond_to do |format|
        format.html { redirect_to @article }
        format.js { }
      end
    end
  end

  private

  def comment_params
    params.require(:comment).permit(:name, :description, :article_id, :user_id)
  end

  def get_article
    @article = Article.find(params[:article_id])
  end
end

任何帮助,谢谢

1 个答案:

答案 0 :(得分:1)

控制器需要

<ActionController::Parameters {"utf8"=>"✓", "comment"=>
{name"=>"123432","description"=>"231424"}, "commit"=>"submit", 
"controller"=>"comments", "action"=>"create", "article_id"=>"5"} 
permitted: false>

在您的表单中,通过为“名称”和“说明”字段声明“名称”属性,您实际上将“名称”字段的名称从comment[name]覆盖为comment_name。所以只需从表单中删除这些名称属性

<%= simple_form_for [@article, @article.comments.build], remote: true do |f| %>
 <%= f.input :name%>
 <%= f.input :description%>
 <%= f.submit :submit, class: "btn btn-default" %>
<% end %>`