开发者

collection_select doesn't let ActiveRecord update its collection when none of options is selected

开发者 https://www.devze.com 2023-01-06 21:56 出处:网络
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 collect

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; Wh开发者_如何学Cen 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消