Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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| [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][].

like image 924
Michał Avatar asked Mar 31 '11 13:03

Michał


2 Answers

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 :)

like image 83
Claudio Acciaresi Avatar answered Sep 28 '22 05:09

Claudio Acciaresi


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

:checked => [2, 3]

Hope it helps someone.

like image 34
John Goodman Avatar answered Sep 28 '22 05:09

John Goodman