Rails 3.2 - collection_select 在我的数组的第一个位置添加一个空条目 [英] Rails 3.2 - collection_select Adding A Null Entry In The First Position Of My Array

查看:58
本文介绍了Rails 3.2 - collection_select 在我的数组的第一个位置添加一个空条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Ruby on Rails 3.2.13 应用程序,其中有一个 collection_select 语句.collection_select 语句位于 fields_for 语句中,我从 collection_select 收集选定的 id 并使用它们填充另一个表.我遇到的问题是 collection_select 语句在存储选定 id 集合的数组中添加了一个空 id 条目.

这是我认为的代码:

<%= 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})%><%结束%>

以下是选择两个选项后数组外观的示例:

"media_topics_attributes"=>{"0"=>{"topic_id"=>["", "2", "47"], "id"=>"1895"}}

我认为数组应该只有两个 ID,2"和47".空值导致更新我的嵌套属性时出现问题,因为错误表明该值不能为空.当为具有相关行的行显示编辑视图时,collection_select 中的正确记录将按预期选择并在列表中突出显示.

如何更改未添加空条目的 collection_select 语句?我不允许 MediaTopic 模型上的任何行添加 topic_id 等于 null.我已经研究了几天.我发现有人遇到了类似的问题,但该问题的所有解决方案都无法解决问题.

任何帮助将不胜感激.

解决方案

在更新操作之前在您的控制器中尝试 params[:media_topic][:topic_ids].delete("").>

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.

解决方案

Try params[:media_topic][:topic_ids].delete("") in your controller before the update action.

这篇关于Rails 3.2 - collection_select 在我的数组的第一个位置添加一个空条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆