RailsCasts Pro episodes are now free!

Learn more or hide this

Samuel Vega Caballero's Profile

GitHub User: innovega

Site: www.innovega.net

Comments by Samuel Vega Caballero


If you are using a FormBuilder, maybe you can prefer use this for generate the checkbox name. For example, if we have a form with nested forms for a has_many association and each of these need a category_ids collection of checkboxes calculate the name of these checkboxes can be a problem. So, I suggest use the object_name method of the FormBuilder object:

<%= hidden_field_tag "#{f.object_name}[category_ids][]", nil %>
<% Category.order(:name).each do |category| %>
    <%= check_box_tag "#{f.object_name}[category_ids][]", category.id, f.object.categories.include?(category) %>
    <%= category.name %>
<% end %>

Note that I use f.object instead of @product too. I think this way is better for use with a FormBuilder.

Finally, as you can see, I use an input hidden for be sure always send a category_ids array, so, I don't need setup this field in the controller.

I hope you find it useful :)