Having kinda trouble with checkboxes. Let’s assume “Order
has_and_belongs_to_many :products” and vice versa. Now let’s assume
there are products with IDs 1, 2 and 3 in the db and I’m editing an
existing Order with the following view:
<% form_for(:order) do |f| %>
<% f.check_box(:product_ids, 1) %>
<% f.check_box(:product_ids, 2) %>
<% f.check_box(:product_ids, 3) %>
<% end %>
First let’s set all checkboxes. The resulting params hash will be:
param[:order][:product_ids] # => [‘1’, ‘2’, ‘3’]
This is perfect as the controller code will do as desired: @order.update_attributes(params[:order]) @order.product_ids # => [1,2,3]
But now the same with all checkboxes NOT set. The params hash:
param[:order][:product_ids] # => nil
Way uncool, because this is what the controller does: @order.update_attributes(params[:order]) @order.product_ids # => [1,2,3]
It would be cool though to have an empty array instead of nil in the
params hash there as this would correctly remove all referenced products
from this order.
Now I could of course add this to the controller: @order.product_ids = [] if @order.product_ids.nil?
But as my view code is generated by a FormHelper plugin, I’d like to
make it work without the need to touch the controller code.
Can I add anything to the view that will ensure the params hash will
return [] rather than nil if no checkbox is set?
You could do this before calling update_attributes:
param[:order][:product_ids] ||= []
This will initialize the product_ids parameter to an empty array if it
is nil.
If you want to make this the default behavior, you’ll need to open up
some Rails code. Not sure exactly where you’d make a change, but it
should be possible in just a few lines of code.
Thanks, but I can’t seem to make that version of the fuction work
either. That’s ok though I’ll look elswhere to find a working example
of what I’m trying to do, just thought this was it.