How do you get fields_for
to submit an array? Everything I've found suggested on SO doesn't work for me.
My params are submitting like this:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"mxHD...VoA==", "callsign"=>"baz", "post"=>{"conversation_attributes"=>{"missives_attributes"=>{"content"=>"Hello"}}}}
but I want them to submit like this, with the square brackets around missives:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"mxHD...VoA==", "callsign"=>"baz", "post"=>{"conversation"=>{"missives"=>[{"content"=>"Hello"}]}}}
I just want to submit a single instance of missive
, but in array form. In other words, an array with single member.
This answer lists all the possible ways to get this working, and I have failed with every single one:
FAIL 1
_post_form.html.erb
<%= f.fields_for :conversation do |ff| %>
<%= ff.fields_for 'missives[]', [] do |fff| %>
<%= fff.text_area :content %>
...
<% end %>
<% end %>
Result: Error: undefined method `id' for []:Array
FAIL 2
It is an ActiveRecord relationship so apparently I do not need getter/setter methods.
<%= f.fields_for :conversation do |ff| %>
<% @missives = [] %>
<%= ff.fields_for :missives, @missives do |fff| %>
<%= fff.text_area :content %>
...
<% end %>
<% end %>
Result: Error (undefined method `content' for []:Array)
FAIL 3
<%= f.fields_for :conversation do |ff| %>
<%= ff.fields_for :missives, @missives do |fff| %>
<%= fff.text_area :content %>
...
<% end %>
<% end %>
Result: does not put square brackets around missives.
FAIL 4
In the controller:
@missives = [Postmissive.new]
In the post form:
<%= f.fields_for :conversation do |ff| %>
<%= ff.fields_for :missives, @missives do |fff| %>
<%= fff.text_area :content %>
...
<% end %>
<% end %>
Result: Error (undefined method `content' for Array).
Current state of code:
post.rb
has_one :conversation, class_name: 'Postconversation', dependent: :destroy
accepts_nested_attributes_for :conversation
postconversation.rb
has_many :missives, class_name: 'Postmissive', dependent: :destroy
accepts_nested_attributes_for :missives
postmissive.rb
belongs_to :conversation, class_name: 'Postconversation', foreign_key: 'conversation_id'
validates :content, presence: true
posts_controller.rb
@post = @character.posts.create(post_params)
...
def post_params
params.require(:post).permit( conversation_attributes: [ missives_attributes: [ :content ] ] )
end
_post_form.html.erb
<%= f.fields_for :conversation do |ff| %>
<%= ff.fields_for :missives do |fff| %>
<%= fff.text_area :content %>
...
<% end %>
<% end %>