3

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I accidentally had m.simple_fields_for in my original code. it should be p.simple_fields_for and p.simple_form_for. I fixed in mine but it won't let me fix in your copy/paste. maybe edit that when you have a sec.
@TimKoelkebeck I just fixed that. I hadn't noticed it when I copied it from your original. Glad that it's all working for you. Enjoy!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.