Here is the form_with view-helper from the Rails "Getting Started" Guide (https://guides.rubyonrails.org/getting_started.html) for the nested Article model Comment or Article.comments:
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
<h2>Add a comment:</h2>
<%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>
<p>
<%= form.label :commenter %><br>
<%= form.text_field :commenter %>
</p>
<p>
<%= form.label :body %><br>
<%= form.text_area :body %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>
Also
class Article < ApplicationRecord
has_many :comments
validates :title, presence: true,
length: { minimum: 5 }
end
and
class Comment < ApplicationRecord
belongs_to :article
end
Now I would like to know if it is possible to use the form_with helper or another helper or helper-combination in order to create or edit a new Article with more than one nested models like Comment, Tag, ... and what further models an Article may be composed of.
... which creates a sane and useful params-Hash (because my own solution with a 'fields_for' form-helper doesn't produce a desired or useful params hash.
This is how the params-hash looks like:
<ActionController::Parameters {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"BeCtYS/U6lugXzzplTEBsMXAiD0x7z28iBUblHiza379p4YqRcd+ykgd49o53oOrC8o+iPhtWnvQQHe0ugCJow==", "article"=>{"parent_article_id"=>"", "title"=>"Überschrift", "text"=>"Toller Text"}, "tags"=>{"name"=>"Rails"}, "commit"=>"Update Article", "controller"=>"articles", "action"=>"update", "id"=>"1"} permitted: false>
The problem is that the controller/article id is not subsumed under the :article key. I don't know how to fix that for strong_parameters and I don't even want to. I would prefer Rails to just function after the principle of least astonishment instead of doing hackery things to get things working.
In this case I hope it's my own ignorance and lack of knowledge regarding form-helpers that prevents Rails from generating a proper params-hash.
Thanks.
Rails should be doing this as you expect. From
accepts_nested_attributes:The params hash you are showing is very strange. It looks like you're manually making disconnected fields like
parent_article_idinstead of actually using the capaibilities ofform_withandfields_for.I'd need to see your view and controller code to see how you've implemented
form_withandfields_forto help you get these params nested the way you want.