check_box
check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")Alias for ActionView::Helpers::FormHelper#checkbox
4Notes
Sending array parameters
Another technique to use when you need to send an array parameter is pass in the :multiple option.
check_box("puppy", "commands", {:multiple => true}, "sit", nil)
check_box("puppy", "commands", {:multiple => true}, "fetch", nil)
check_box("puppy", "commands", {:multiple => true}, "roll_over", nil)
If all checkboxes are checked, the paramters will be: "puppy" => {"commands" => ["sit", "fetch", "roll_over"]}
NOTE: because of the gotcha, the hidden fields will be inserted and any unchecked boxes will be sent as "" (empty string). You will need to filter those values out in your model:
class Dog < ActiveRecord::Base
def commands=(commands)
commands.reject(&:blank?)
end
end
Have the check_box checked by default
To have the check box checked by default, pass either :checked => true or :checked => 'checked' in the options. See ActionView::Helpers::InstanceTag#to_check_box_tag for details.
Have check_box checked by default
In addition to comment below, you can make a column with default value so in your forms it will be enabled by default and behave correctly with validation errors unlike :checked => true
==== in your migration
add_column :accounts, :ssl_enabled, :boolean, :default => 1
Use strings as parameters, not booleans
I just stumbled across this somewhere in our codebase. The first example is faulty, the second one is correct.
= f.check_box :public, {}, true, false
# <input id="event_public" name="event[public]" type="checkbox" value="true" />
and:
= f.check_box :public, {}, "true", "false"