Fields_for and Multiple Checkboxes
May 23rd, 2008
Found a bit of a gotcha when building a form recently using form_for, fields_for and the check_box helper. Because Rails adds a hidden field for each checkbox and fields_for for new objects produces ids like ‘users_invites__selected’, if you try to generate multiple new objects in the same form things can get a little confused. I found that when selecting a single checkbox things worked ok, but when selecting multiple the values would bleed across each other. I haven’t investigated this very far just switched to check_box_tag instead (no hidden field).
Actually just found this post mentioning that the checkboxes might be broken in Rails 2.0.2. Which could be the cause of the issue.
May 30th, 2008 at 04:36 AM this is my workaround: <% form.fields_for :foo_ids do |f| %> <% @foos.each do |foo| %> <%= f.check_box [], {:checked=>...}, foo.id, nil %> <% end %> <% end %> The magic lies in that nil. It makes the hidden checkboxes deliver "" instead of "0", which is ignored in the controller.
June 4th, 2008 at 05:53 PM @eliguh - cool, thanks for sharing.