how to preselect an association checkbox using simple_form

I have this piece of code, while using simple_form:

= simple_form_for :report do |f|
  = f.association :presets,
    :collection => @account.presets.collect{ |p| [,] },
    :as => :check_boxes

How can I preselect a specific preset checkbox, knowing that the ID of this preset is passed within params[:preset_id]? The checkboxes' HTML name attributes are report[preset_ids][].


According to the simple_form documentation:

The association helper just invokes input under the hood, so all options available to :select, :radio and :check_boxes are also available to association. Additionally, you can specify the collection by hand, all together with the prompt:

   f.association :company, :collection
      => => 'name'), :prompt => "Choose a Company"

So, you should use something like this:

= simple_form_for :report do |f|
  = f.association :presets,
    :collection => @account.presets.collect{ |p| [,] },
    :as => :check_boxes,
    :checked => params[:preset_id]

I don't have experience with simple_form, but this might help :)

An update for everybody. the :selected option did not work for me. I used:

:checked => [2, 3]

Hope it helps someone.

f.association Really did the trick, thanks :), for preselecting, saving, and everything, I don't have reputation enough to vote up your answer (@claudio-acciaresi) that's why I'm commenting here...

This is my snippet:

<%= f.association :association, collection: Model.all, 
      value_method: :id, label_method: :name, 
      as: :check_boxes, include_blank: false %>

Replace symbol :association with the current has_many from the model. Replace Model.all, for your source data.

Hope it gets useful for someone else :)


Don't forget to cast params[:preset_id] to integer:


Need Your Help

Popularity of Git/Mercurial/Bazaar vs. which to recommend

svn git version-control mercurial bazaar

Going by the number of questions on this site for these three distributed version control systems, it seems like Git either

CSS: Top vs Margin-top

css css-position

I'm not sure if I fully understand the difference between these two.