4

我已经尝试了所有视频和文章,但仍然找不到将 fields_for collection_select 值添加到 strong_params 中的白名单的解决方案。我花了几天时间试图弄清楚这一点(并问了很多人)。如果有人能花时间帮助我,我将不胜感激!

我在 List 和 Topic 之间有一个多对多的关联,List_Topic 充当连接模型。使用 form_for,我为 List 的实例 (@list) 创建了一个表单,然后为 fields_for :list_topics 创建了一个表单。在字段中,我创建了一个由 Topic.all 填充的 collection_select。

<br>
 <%= form_for(@list) do |f| %>
  <%= f.label :subject %>
  <%= f.text_field :subject %>
<br>
<br>

 <%= f.fields_for :list_topics do |ff| %>
  <%= ff.label "Choose a Topic:"  %><br>
  <%= ff.label :content %>
  <%= ff.text_field :content %>
  <%= ff.collection_select(:id, @all_topics, :id, :name, {}, {multiple: true}) %>
 <% end %>

 <%= f.submit %>
<% end %>

在我的列表控制器中,我有:

class ListsController < ApplicationController

  def new
    @list = List.new
    @all_topics = Topic.all
    @list.list_topics.build 
  end

  def create
    @list = List.new(list_params)
  end

private

  def list_params
    params.require(:list).permit(:subject, :list_topics_attributes =>    [:topic, :content, :topic_ids, :id, :ids])
  end  

end

fields_for 表单中的参数传递为:

list_topics_attributes"=>{"0"=>{"content"=>"Hey", "id"=>["", "2"]}}} 

虽然strong_params 被列入@list 白名单,并且我能够通过:list_topics_attributes 获得我制作的custom_attribute writer 来识别fields_for 中的:content 参数,但我无法将通过的strong_params 中的:id 参数列入白名单无论我尝试什么或关注我的文章/视频,都可以通过 collection_select 进入。他们根本不会出现。

我这里也有 git repo。表格在列表/新建下

https://github.com/jwolfe890/Top5/blob/master/app/views/lists/new.html.erb

非常感谢您的任何见解!

4

1 回答 1

3

有人刚刚在这里,但他的评论看起来像是被删除了。我只是想感谢他,因为他的解决方案奏效了:

params.require(:list).permit(:subject, :list_topics_attributes => [ :content, id: []])

本质上,由于 id 位于 list_topics_attributes 散列中的数组中,因此 :id 字段必须在 list_topics_attributes 散列中传递,并且 :id 字段也需要分配给它的数组。

谢谢!

于 2017-01-27T00:01:22.580 回答