Skip to content

Fields_for and Multiple Checkboxes

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 Comments

  1. eliguh wrote:

    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.

    Friday, May 23, 2008 at 9:06 am | Permalink
  2. @eliguh – cool, thanks for sharing.

    Friday, May 23, 2008 at 9:06 am | Permalink
  3. Kenny Vargas wrote:

    pcvbgy7z7ytt3270

    Friday, May 23, 2008 at 9:06 am | Permalink