I was trying to setup an HABTM list with a checkbox, similar to Ryan Bates’ railscast. The problem was the empty http posts when all checkboxes are cleared.
The code that I was emulating is:
# products_controller.rb def update params[:product][:category_ids] ||= [] #... end
The problem I was having is that
params[:product]
was nil as the http post sent nothing because I only had checkboxes on my form. Defaulting to
[]
wasn’t valid for the
update_attributes
method.
The hack that I finally came up with was like this:
# products_controller.rb def update if params[:product].nil? @products.categories = [] else @products.update_attributes(params[:product]) end redirect_to :action => :index end
So it turns out, in this HABTM scenario, one can address the entire list of categories with an array.




Or just include a hidden field in the form:
hidden_field_tag(“product[category_ids][]“, “”, :id => nil)
Put this before the first checkbox.
Comment by Scott Johnson — October 23, 2009 @ 2:12 pm