Michał
Michał

Reputation: 373

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

Upvotes: 17

Views: 11578

Answers (4)

Claudio Acciaresi
Claudio Acciaresi

Reputation: 32351

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

Upvotes: 30

kainlite
kainlite

Reputation: 1061

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

Regards.

Upvotes: 1

John Goodman
John Goodman

Reputation: 1098

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

:checked => [2, 3]

Hope it helps someone.

Upvotes: 25

rbnoob
rbnoob

Reputation: 99

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

params[:preset_id].to_i

Upvotes: 0

Related Questions