Preselect Check box with Rails Simple_form

31,467

Solution 1

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

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

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

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

Solution 2

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

:input_html => { :checked => true }

So, it would become:

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

Hope that helps!

Solution 3

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] %>

Solution 4

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

def new
  Object.new(my_boolean: true)
end

Solution 5

This should work:

= f.input :some_flag, :input_html => { :value => '1' }
Share:
31,467
Drew
Author by

Drew

Updated on June 13, 2020

Comments

  • Drew
    Drew about 4 years

    I'm using Simple_Form with Rails 3 and it's great. I have a simple question. I can create a check box using f.input if the type is boolean behind the scenes. However, I would like it to be preselected as true.

    Is there a way to do this via the view?