Dennis
Dennis

Reputation: 1018

Nested Attributes, parent with optional child

I have two model classes, say parent and child. Parents are created first, and then a child can be added.

I'm trying to have an edit page where you can edit the information on for the parent and possibly add a child.

I have it set so that the parents can access child attributes:

has_one :child
accepts_nested_attributes_for :child

And in my view to edit parent information, I have a form that shows all the parent information, and then fields to either edit existing child information or add a new child:

<%= form_for(@parent, :as => :parent, ...  %>       
    <%= form.text_field(:field_one) %>
    <%= form.text_field(:field_two) %>

    <%= form.fields_for @child do |child| %>  
        <%= child.text_field(:child_field_one) %>
        <%= child.text_field(:child_field_two) %>
    <%end%>
<%end%>

The problem is that the only way I can get this to work is to have my parent edit controller create a new child and associate it with the parent before rendering the view. Then when the user tries to save, my controller checks to see if the child fields are empty and deletes the newly created child if it is. One problem with this is that it creates an empty child (assuming a child doesn't exist) every time the edit page is loaded, and then saves it to the database (which I don't want)

Is there an elegant way of showing the fields for a non-existent child on the parent edit page without creating a new child before rendering? Ideally I want everything on a single form. I'm pretty sure I can come up with a way of doing this in multiple forms with multiple save buttons.

Upvotes: 0

Views: 876

Answers (2)

Salil
Salil

Reputation: 9722

If you don't want the child object to be saved to database unless the user has edited it, one way is to have model validations on a child object that will prevent it from being saved.

Upvotes: 0

Terra Kestrel
Terra Kestrel

Reputation: 20304

Maybe I don't fully understand what you're trying to do, but if you are using a fields_for tag, you need an object. The only other way to do that is to use the symbol and call it as:

<%=form.fields_for :child do |child| %>

But (assuming that's even still valid in Rails 3) that's effectively equivalent to

<%=form.fields_for Child.new do |child| %>

which is the same as

@child = Child.new

In the controller action.

I'm pretty sure that, in order to use the form helper, you need an object to iterate over.

Upvotes: 2

Related Questions