bo-oz
bo-oz

Reputation: 2872

How to set association checkboxes to true by default in Rails

I want to check my association checkboxes by default. I tried by setting the checked attribute to an array of plucked Company IDs.

= f.association :selected_companies, label_method: :name, as: :check_boxes, collection: Company.order(:name), :checked => Company.pluck(:id)

This seems to work, but when there are form field errors, the checkboxes are reset on the next request. I'd like to persist the users choice in these cases.

Any ideas?

Upvotes: 2

Views: 53

Answers (1)

smathy
smathy

Reputation: 27971

Change your view to checked: @company_ids and then in your controller set that to Company.pluck(:id) in your edit action, but to @your_main_object.selected_company_ids in your update action.

Upvotes: 2

Related Questions