Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

label_tag and checkbox_tag problem in rails

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>
like image 856
corroded Avatar asked Feb 15 '11 11:02

corroded


2 Answers

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[]"
like image 196
Taylored Web Sites Avatar answered Oct 11 '22 23:10

Taylored Web Sites


This worked great for me:

= f.label :remember_me do
    = f.check_box :remember_me
    Remember me

There's no need to close "do" block. It gets closed automatically because of indentation. Check out the last example from Rails API: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-label

like image 35
Viktor Avatar answered Oct 11 '22 22:10

Viktor