Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

Regards.

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

params[:preset_id].to_i
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top