check_box_tag
check_box_tag(name, value = "1", checked = false, options = {})Creates a check box.
5Notes
Pass id collections with check box tags
It can be useful to pass a collection of ids to a controller, especially in the case of a has_many relationship, for example:
User has_many Roles
In your view you could have something like:
-
<% @roles.each do |role| %>
- <%= check_box_tag 'role_ids[]', role.id -%> <%= h role.name -%> <% end %>
Note the square brackets after role_ids - this is important for passing a collection through to the controller.
If you place this in a form and submit it, you can expect to see a param passed into the controller that looks like: "role_ids"=>["1", "2", "3"]
Set ids when using a collection of values
The trick to getting the helper to populate a unique HTML ID and for rails to recognise a collection is to give the helper a unique 'name' and to set the :name symbol to parameter with an array symbol '[]'.
<% Cars.each do |c| %>
<%= check_box_tag "car_ids[#{c.id}]", c.id, :name => "car_ids[]" %>
<% end %>
Use dom_id( resource_instance ) to create the HTML id
In the notes on this page people use: car_ids_#{c.id}
But you can use this function in stead:
dom_id(c)
Set ids when using a collection of values (cont.)
Concerning greeneggs614's post:
The following version would be a bit more intention revealing while providing the same output:
<% Car.each do |c| %>
<%= check_box_tag "car_ids[]", c.id, :id => "car_ids_#{c.id}" %>
<% end %>
Set ids when using a collection of values (cont.)
Regarding schmidt's post.
The following will not have the expected behavior:
<% Car.each do |c| %>
<%= check_box_tag "car_ids[]", c.id, :id => "car_ids_#{c.id}" %>
<% end %>
But, if you put the "checked" option to false (or true), it will.
<% Car.each do |c| %>
<%= check_box_tag "car_ids[]", c.id, false, :id => "car_ids_#{c.id}" %>
<% end %>