4

I’ve tried every video and article and still can’t find a solution to getting fields_for collection_select values to whitelist in strong_params. I’ve spent days trying to figure this out (and asked a number of people). If anyone could take the time to help I would be immensely thankful!

I have a many-to-many association between List and Topic, with List_Topic acting as the join model. Using form_for, I created a form for an instance(@list) of List and then a fields_for :list_topics. Within the fields for, I’ve created a collection_select, which is populated by Topic.all.

<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 %>

In my Lists Controller I have:

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

The params from the form for the fields_for are passed in as:

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

While the strong_params are whitelisted for @list, and I am able to get the custom_attribute writer I made to recognize the :content params in the fields_for through :list_topics_attributes, I have not been able to whitelist the :id params in the strong_params that are passed in through the collection_select no matter what I try or articles/videos I follow. They simply don't appear.

I also have the git repo here. The form is under lists/new

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

Thank you tremendously for any insight!

Dog
  • 2,726
  • 7
  • 29
  • 66

1 Answers1

3

Someone was just on here, but his comments look like they were deleted. I just wanted to thank him because his solution worked:

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

Essentially, since the ids are in an array within the list_topics_attributes hash the :id field has to be passed in the list_topics_attributes hash and THAT :id field also needs to have an array assigned to it.

Thank you!

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Dog
  • 2,726
  • 7
  • 29
  • 66