Home > Mobile >  How to prevent options_from_collection_for_select from storing an empty string in Ruby on Rails?
How to prevent options_from_collection_for_select from storing an empty string in Ruby on Rails?

Time:08-15

I have a rails application and in one of my forms, I am using options_from_collection_for_select to choose multiple options. But in the server, it is storing an empty string, after which I am getting an error since that field is a foreign key and it must exist after form creation.

Here is how my controller looks like:

def product_type_params
  params.require(:product_type).permit(:name, property_types: [])
end

And my form in the view file (I am using HAML, so .my-5 is a class name and a div):

.my-5
  = form.label :property_types
  = form.select :property_types, options_from_collection_for_select(PropertyType.all, :id, :name), {}, { multiple: true }

And here is what I am getting in the server:

Parameters: {"authenticity_token"=>"[FILTERED]", "product_type"=>{"name"=>"Home L", "property_types"=>["", "1", "2"]}, "commit"=>"Create Product type"}

Here, I am getting an empty string in the "property_types" collection.

My question is how can I prevent it from being stored into the collection after the form creation?

CodePudding user response:

When you accept nested attributes on the parent model you can supply a proc to reject accepting the attribute. You can read more at https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for

  • Related