views:

13

answers:

1

I have has_and_belongs_to_many association between two models.

I made use of collection_select to represent the other model in this association in a form. When I tried to deselect options in collection_select, collection_select doesn't post its empty value and, thus, it doesn't let ActiveRecord pass any update clause to the database.

e.g. Parameters are like; When onptions selected; Parameters: {"name_of_model"=>{"name"=>"de2", "other_model_ids"=>["1", "3"]}

When none selected; Parameters: {"name_of_model"=>{"name"=>"de2" }

Does anyone know a workaround for this?

A: 

You need to set the other_model_ids parameter to be an empty array if it is not passed to the controller action:

params[:name_of_model][:other_model_ids] ||= []

This will ensure that if there is no selection then the model will be updated correctly so that it has no associated model IDs.

John Topley
Ah, thanks. I tried to figure out this problem by tweaking erb file and didn't come up with this idea. Thanks a lot
suzukimilanpaak
@suzukimilanpaak If my answer helped you then please accept it by clicking the tick to the left of the answer.
John Topley