多个 collection_select 数组中的第一项始终为空白

first item in array from the multiple collection_select is always blank

新表格的相关部分如下所示:

  <%= f.fields_for :event_artists do |fea| %>
    <%= fea.collection_select :artist_id, Artist.all, "id", "name", {include_blank: true}, {multiple: true} %>
  <% end %>

在日志上,你可以看到数组的第一项总是空白,即使我没有 select 空白字段

"event_artists_attributes"=>{"0"=>{"artist_id"=>["", "2", "5"]}}}

有办法解决这个问题吗?也许,如果空白字段被 selected,那么在这种情况下,实际的 event_artists 不能被 selected,反之亦然?

我认为问题与参数的顺序有关。我查看了 collection_select 并在我正在开发的应用程序中尝试了以下代码。

<%= collection_select(:category, :category_id, Category.all, :id, :name, {}, {multiple: true}) %>

更新:

<%= fea.collection_select :artist_id, Artist.all, "id", "name", {prompt: true}, {multiple: true} %>

artist_id很重要。在另一种形式上,您可能完全省略了艺术家 select,在这种情况下,artists 关联不应受到影响。

如果包含艺术家 select,并且您取消 select 所有艺术家,则需要将这些艺术家从 artists 关联中删除。当没有 selected 时,正常的 HTML 行为根本不会在 PUT 中包含 artist_id 参数。在这种情况下,您的控制器会认为您根本不想修改 artists 关联。

为了解决这个问题,collection_select 包含一个带有空白值的隐藏字段,让控制器知道表单打算更改 artists 关联。如果没有艺术家被 selected,数组中的空白元素将确保所有艺术家都从关联中删除。