简体   繁体   中英

ActionController::ParameterMissing (param is missing or the value is empty: category

I have this simple code which I submit using ajax request

<%= form_for(@category) do |f| %>
  <% if @category.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2>

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

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :enabled %><br>
    <%= f.check_box :enabled %>
  </div>
  <div class="actions">
    <%= f.submit "Create Category", :id => "submit__my_form" %>
  </div>
<% end %>


<script type="text/javascript">
  $(document).on('click', '#submit__my_form', function(event) {
   event.preventDefault();
  console.log($('#new_category').attr('action'));

    $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: $('#new_category').attr('action'),
      data: $("#new_category").serialize(),
//      data: {name: "my name"},
      dataType: "json",
      processData: false,
      contentType: false,
      success: function (result) {
        return false
      },
      error: function () {
        window.alert("Something went wrong! Please try again");
      }
    });
  });
</script>

I get this error after I submit the form

Started POST "/categories" for 127.0.0.1 at 2015-12-01 16:15:57 +0100
Processing by CategoriesController#create as JSON
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 5]]
Completed 400 Bad Request in 34ms (ActiveRecord: 0.4ms)

ActionController::ParameterMissing (param is missing or the value is empty: category):
  app/controllers/categories_controller.rb:73:in `category_params'
  app/controllers/categories_controller.rb:28:in `create'

in the log it point out these two lines as error, line 73

 def category_params
    78:  params.require(:category).permit(:name, :enabled, :user_id)
    end

and line 28

 def create
 28:   @category = current_user.categories.build(category_params)  #  Category.new(category_params)

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

How can I solve this problem? I found many solution on internet but it is not working for me. I think I am missing something in ajax call.

Looks like you're missing the category parent key in the params. Since you're using strong params, category_params is expecting something like {category: { name: 'blah', enabled: true }} , but most likely getting { name: 'blah', enabled: true } . Check the logs to see which parameters are passed to your create action.

I would use the remote option for submitting your form since calling serialize() on the form data doesn't play nicely with strong params.

First, change your form_for to: <%= form_for(@category, remote: true) do |f| %> <%= form_for(@category, remote: true) do |f| %>

Then, a more Rails-friendly Ajax submit:

$(document).ready(function() {
  $("#new_category").on("ajax:success", function(e, data, status, xhr) {
    return false;
  }).on("ajax:error", function(e, xhr, status, error) {
    window.alert("Something went wrong! Please try again");
  });
});

You can find more info in the Rails docs on unobtrusive Javascript.

You missed the right content type application/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8 , try this ajax call instead (comment line contentType: false too):

$.ajax({
    type: "POST",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    url: $('#new_skill').attr('action'),
    data: $('#new_skill').serialize(),
    //data: {name: "my name"},
    dataType: "JSON",
    processData: false,
    //contentType: false,         
    success: function (result) {
        alert(result);
    },
    error: function () {
        window.alert("Something went wrong! Please try again");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM