label_tag and checkbox_tag problem in rails

corroded picture corroded · Feb 15, 2011 · Viewed 10.3k times · Source

I want my checkboxes to be usable so I usually add label fors to the checkboxes so you can select the text instead of having to "aim" for the checkbox.

Problem is, what if I am using a nested attributes form in rails? I have this code for now:

%ul
  - test_category.test_cases.each do |test_case|
    %li
      = check_box_tag "job_test_cases[]", "#{test_case.id}", test_case.id
      = label_tag "test_case_#{test_case.id}", test_case.name

problem with this is that it produces this:

<li>
  <input type="checkbox" value="70" name="job_test_cases[]" id="job_test_cases_" checked="checked">
  <label for="test_case_70">Blah blah</label>
</li>

whereas I wanted it to be like this:

<li>
  <input type="checkbox" value="70" name="test_case_id[]" id="test_case_70" checked="checked">
  <label for="test_case_70">Blah BLah blah/label>
</li>

Answer

Taylored Web Sites picture Taylored Web Sites · Dec 3, 2011

I was able to match the checkbox with the label as follows:

In the checkbox: I used the check_box_tag, specifying the specific item name (role here) as the index of the array to produce the id with a value in it. I passed the :name hash value to override the name specified in the check_box_tag, so that it does not have the id:

check_box_tag "user[roles][#{role.to_s}]", role.to_s, @user.has_role?(role), :name => "user[roles][]"

which generates the following HTML:

<input id="user_roles_ROLE1" name="user[roles][]" type="checkbox" value="ROLE1" />

In the label, I specified the id using the array name + '_' plus the item name (role here), to properly point to the id in the label:

label_tag "user_roles_#{role}", cur_role.role_name, :class => 'span_after_label'

which generates the following HTML:

<label class="span_after_label" for="user_roles_ROLE1">User</label>

When the PUT is sent to the controller, the params have the following fields:

"user"=>{ ..., "roles"=>["ROLE1", "ROLE2", "ROLE3"], ... }

which is the role names for all of the checked roles.

Thus for your code, I would try the following:

check_box_tag "test_case_id[#{test_case.id}]", "#{test_case.id}", test_case.id, :name => "test_case_id[]"