method

check_box

check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
public

4Notes

Sending array parameters

snatchev · Oct 13, 201013 thanks

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

bquorning · Jun 10, 20095 thanks

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

spectator · Oct 15, 20094 thanks

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

kasper_grubbe · Jul 23, 20133 thanks

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"