views:

634

answers:

2

How do you set a custom id when using a check_box_tag helper in rails?

I have a loop which creates a bunch of checkboxes based on a collection:

- subject.syllabus_references.each do |sr|
      = check_box_tag 'question[syllabus_reference]', sr.id, :id => sr.id
      = label_tag sr.id, sr.name

I would like to set a custom id so that my Label for the checkbox works correctly but I can't seem to figure out how (:id => sr.id does not work...).

The problem might also be with the way I've defined the label, so if I can get that to reference the correct check box without setting a custom id then that would be fine also...

A: 

Think I figured it out...

- subject.syllabus_references.each do |sr|
  = check_box_tag "question[syllabus_reference][#{sr.id}]", sr.id
  = label_tag "question[syllabus_reference][#{sr.id}]", sr.name

This works but if you have a better way let me know!

Ganesh Shankar
+1  A: 

I used this in my application to create checkbox tags from collection and submit an array of them:

<% @cursos.each do |c| %>
  <span class='select_curso'>
    <%= check_box_tag "vaga[curso_ids][]",
      c.id, (checked = true if form.object.curso_ids.include?(c.id)) %>
    <%= label_tag "vaga[curso_ids][][#{c.id}]", c.nome %>
  </span>
<% end %>

So in params, I have an array "curso_ids"=>["1", "3", "5"] instead of a string "curso_ids"=>"5". If you want to return a single value, use vaga[curso_id], otherwise use vaga[curso_ids][] to return an array.

nanda