Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a check box in Haml using check_box_tag

Can someone tell me how to set these check boxes to checked? I'm sure it's simple, but after an hour of trying i think I need to ask! Thanks!

= form_tag movies_path, :id => 'ratings_form', :method => :get do
  Include: 
  - @all_ratings.each do |rating|
    = rating
    = check_box_tag "ratings[#{rating}]", 
  = submit_tag 'Refresh', :id => 'ratings_submit'
like image 805
user1756646 Avatar asked Oct 18 '12 14:10

user1756646


3 Answers

Ref check_box_tag

check_box_tag "ratings[#{rating}]",  1, !!(rating.rating)

Your 2nd parameter must be value of checkbox

Your 3rd parameter must be a boolean condition which return true/false and depends on it checkbox is checked/unchecked

like image 186
Salil Avatar answered Oct 23 '22 13:10

Salil


check_box_tag "ratings[#{rating}]",  1, @selected.include?("#{rating}")

where @selected is an array with the element selected.

like image 44
Matias Yaryura Avatar answered Oct 23 '22 13:10

Matias Yaryura


According to the api dock, check box tag takes the following options:

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

This means the first value is the name, the second value is a 'value' and the third value is whether the box is checked, which is default to false. So, in order to check or uncheck the box you can do the following:

- if (some condition)
  = check_box_tag "ratings[#{rating}]", "anystring", true
- else 
  = check_box_tag "ratings[#{rating}]" 

The second line just puts a random string into the value field because in this case it does not matter.

like image 35
FletchRichman Avatar answered Oct 23 '22 12:10

FletchRichman