How can I submit (post/put) checkbox values to a Rails 3 controller via ajax without wrapping the checkboxes in a form? In other words, how do I serialize the checkboxes to an array with no form.
Any help with this will be great appreciated. Thanks!
Here is what I am trying to do specifically:
View:
<ul>
<%= @items.each do |item|
<li>
<%= checkbox_tag_tag "item_ids[]", item.id, false,
:class => "item-checkbox" %>
<%= item.name %>
</li>
<% end %>
</ul>
Controller:
class ItemsController < ApplicationController
respond_to :html, :js, :json
.
.
.
def update_multiple_items
Item.update_all(
{ :category_id => params[:category_id] },
{ :id => params[:item_ids] }
)
end
end
Javascript (jQuery):
$("#update-link").click(function() {
var categoryId = 2;
var itemsArray = $(".item-checkbox:checked").serializeArray();
$.ajax({
type: "PUT",
url: "items/update_multiple_items",
data: {
category_id: categoryId,
items_ids: itemsArray
},
dataType: "script"
});
});
I get an Active Record error with the following info:
!ruby/hash:ActiveSupport::HashWithIndifferentAccessname: item_ids[]value: ''303'''
Here are the request parameters:
Parameters:
{"parent_id"=>"7", "item_ids"=>{"0"=>{"name"=>"item_ids[]", "value"=>"302"}, "1"=>
{"name"=>"item_ids[]", "value"=>"303"}}}