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.

3 Responses to “Fields_for and Multiple Checkboxes”

  1. 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. @eliguh – cool, thanks for sharing.

  3. pcvbgy7z7ytt3270

Sorry, the comment form is closed at this time.