我有这个简单的代码,我使用ajax请求提交
<%= 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>
我提交表单后出现此错误
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'
在日志中它指出这两行是错误,第73行
def category_params
78: params.require(:category).permit(:name, :enabled, :user_id)
end
和第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
我该如何解决这个问题?我在互联网上找到了很多解决方案,但它对我不起作用。我想我在ajax电话中遗漏了一些东西。
答案 0 :(得分:0)
看起来你错过了参数中的category
父键。由于您使用的是强参数,category_params
期望{category: { name: 'blah', enabled: true }}
,但最有可能获得{ name: 'blah', enabled: true }
。检查日志以查看将哪些参数传递给您的创建操作。
我会使用remote
选项提交您的表单,因为在表单数据上调用serialize()
并不能很好地使用强参数。
首先,将您的form_for
更改为:<%= form_for(@category, remote: true) do |f| %>
然后,更多Rails友好的Ajax提交:
$(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");
});
});
您可以在Rails docs上找到有关不引人注目的Javascript的更多信息。
答案 1 :(得分:0)
您错过了正确的内容类型application/x-www-form-urlencoded; charset=UTF-8
,请尝试此ajax调用(注释行contentType: false
):
$.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");
}
});