Scott Rutherford

Life on and off the Rails

 

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.

2 Responses to “Fields_for and Multiple Checkboxes”

  1. eliguh Says:
    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.
  2. Scott Rutherford Says:
    @eliguh - cool, thanks for sharing.
Leave a Reply

This blog used the Shay theme as a base and is powered by Mephisto