I want a form to edit a single new child object and the parent object in one go (in a has many relationship). If I create a new child in the controller with @child = @parent.children.new
, the following works, but it displays input fields for all existing children.
<%= simple_form_for @parent do |p| %>
<%= p.input :parent_attribute %>
<%= p.simple_fields_for :children do |c| %>
<%= c.input :child_attribute %>
<% end %>
<% end %>
How can I display form input fields for only the single new child that was created?
If you want to display the new single child form within the parent form, you can do this:
<%= simple_form_for @parent do |p| %>
<%= p.input :parent_attribute %>
<%= p.simple_fields_for :child, @child do |c| %>
<%= c.input :child_attribute %>
<% end %>
<% end %>
Note that you have to specify both the child model name, as well as the child model object to simple_fields_for
(or fields_for
) to reference a specific model object.
If you only want to display the new single child form, you can do this:
<%= m.simple_form_for @child do |c| %>
<%= c.input :child_attribute %>
<% end %>
This will create the form only for the new child record.