how to preselect an association checkbox using simple_form

Michał picture Michał · Mar 31, 2011 · Viewed 11.2k times · Source

I have this piece of code, while using simple_form:

= simple_form_for :report do |f|
  = f.association :presets,
    :collection => @account.presets.collect{ |p| [p.name, p.id] },
    :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][].

Answer

Claudio Acciaresi picture Claudio Acciaresi · Apr 15, 2011

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
      => Company.active.all(:order => '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| [p.name, p.id] },
    :as => :check_boxes,
    :checked => params[:preset_id]

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