method

check_box_tag

check_box_tag(name, value = "1", checked = false, options = {})
public

Creates a check box.

5Notes

Pass id collections with check box tags

autonomous · Jul 23, 200814 thanks

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

greeneggs614 · Jun 14, 20111 thank

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

webdevotion · Jun 17, 20131 thank

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.)

schmidt · Jan 10, 2012

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.)

rafaelkin · Jul 20, 2012

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 %>