I have a Ruby on Rails 3.2.13 application where I have a collection_select statement. The collection_select statement is in a fields_for statement where I gather selected ids from the collection_select and use them to populate another table. The problem I am having is that the collection_select statement adds a null id entry in the array that stores the collection of selected ids.
Here is my code in my view:
<%= f.fields_for :media_topics do |media_topic| %>
<%= media_topic.label :topic, "Topics" %><%= media_topic.collection_select(:topic_id, Topic.order("name_en"), :id, :name_en, {}, {multiple: true}) %>
<% end %>
Here is an example of how the array looks after selecting two options:
"media_topics_attributes"=>{"0"=>{"topic_id"=>["", "2", "47"], "id"=>"1895"}}
I would think the array should only have two ids, "2" and "47". The null value is causing a problem with updating my nested attributes because of an error saying that the value can't be blank. When the edit view is displayed for a row with related rows that exists the correct records in the collection_select are selected and highlighted in the list as expected.
How do I change the collection_select statement where it does not add the null entry? I do not allow any rows on the MediaTopic model to be added with topic_id equal to null. I have been researching this for several days. I found one where a person had a similar issue but none of the solutions on that question work to solve the problem.
Any help would be appreciated.
According to @vinodadhikary the null entry in the array is working as expected in Rails 3. I recently rewrote this application in Rails 4. I completely rewrote the logic by first using has_many through to relate all my tables. I also replaced the fields_for logic by just using a collection_select statement. I added include_hidden = false in the first {} and the null entry does not appear in the array. I asked a similar question a few days ago and after a lot of searching I came up with a solution. Details are in the link below.
Try params[:media_topic][:topic_ids].delete("")
in your controller before the update action.
来源:https://stackoverflow.com/questions/18166953/rails-3-2-collection-select-adding-a-null-entry-in-the-first-position-of-my-ar