[ACCEPTED]-Preselect Check box with Rails Simple_form-checkbox

Accepted answer
Score: 104

If you don't want to, or cannot update your 4 migration to do 'PerfectlyNormal's answer, then 3 you can add the following to the end of 2 your f.input:

:input_html => { :checked => true }

So, it would become:

= f.input :some_flag, :input_html => { :checked => true }

Hope that 1 helps!

Score: 16

the best way would be to set the default 8 value in your model, something like

create_table :my_table do |t|
  ...
  t.boolean :my_boolean, :default => true
  ...
end

which 7 simple_form will pick up on, and set the checkbox to 6 be checked by default.

A simpler way is to 5 do it as Dave says, and just force the value 4 to 1, but if a validation fails, and you 3 display the form again, it will still be 2 checked, regardless of how it looked when 1 the form was submitted.

Score: 13

It Worked for me which checks only one checkbox with value of "None"

<%= f.input :notify, label: "Notification", as: :check_boxes, collection: ["None", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], :item_wrapper_class => 'inline', :checked => ["None", true] %>

0

Score: 3

I just stumbled over this post and what 3 worked for me is similar to the latest answer 2 - but shorter. Just initialize the Object 1 with the wished setting:

def new
  Object.new(my_boolean: true)
end
Score: 2

This should work:

= f.input :some_flag, :input_html => { :value => '1' }

0

Score: 2

In my opinion, the rail way to do this would 2 be to set the value of the attribute in 1 the controller:

@some_object.some_flag = 1

Score: 0

For Rails 6+, you can simply do:

<%= f.check_box :remember_me,  checked: true %>

0

Score: 0

If you do the following, as in the highest 15 rated answer (and as noted by @PerfectlyNormal) you 14 are essentially hard-coding the state for 13 every page load:

= f.input :some_flag, :input_html => { :checked => true } # don't do this

If you are using Rails-style server validation, this 12 will have the unintended side effect of 11 resetting the user's choice when validation 10 fails.

Defaulting it in the model is ideal 9 if the default value is static. In some 8 cases though, the default value is driven 7 by some business rule, so setting it at 6 runtime is desired. For example, in my case, I 5 wanted to default a checkbox to true, but 4 only for certain types of organizations.

What 3 you want is to default the value only when it is not already set, otherwise 2 use the user-selected value. Here's how 1 I handled this:

- is_checked = @org.is_special.nil? ? true : @org.is_special?
= f.input :some_flag, :input_html => { :checked => is_checked }

More Related questions