Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a check box default to being "checked" in Rails 1.2.3?

How can I make a check box default to being "checked" when it is initially displayed?

I've not found a "Rails" way to do this (that works) so I did it with JavaScript. Is there a proper way to do this in Rails? I'm using Rails 1.2.3.

like image 333
daustin777 Avatar asked Feb 25 '09 15:02

daustin777


People also ask

How do you create a check box in rails?

check_box inside a form builder, plus you have to add a label to display it. The construct you are using just generate the <input type="checkbox" value="something" /> and not the label, that you have to add, just like text or with a <%= label_tag 'whatever' %> .


2 Answers

Rails 3.x

= form_for(@user) do |f|   = f.check_box :subscribe, {checked: true, ...} 

This sets the checked state to true and should work fine. Note the ruby 1.9.x syntax of the hash, for ruby 1.8.x use hash tag format {:checked => true, ...}

like image 120
Matt Smith Avatar answered Oct 12 '22 05:10

Matt Smith


If you're using check_box in the context of a form, then the check box will show whatever value that field has.

@user = Person.find(:first) @user.active = true check_box 'user', 'active'  #=> will be checked by default 

If you're using check_box_tag, the third parameter is the initial state (check_box_tag doc):

check_box_tag "active", 1, true 
like image 29
wesgarrison Avatar answered Oct 12 '22 05:10

wesgarrison