Making an child before the parent is commited to DB

Say I have a model something like this
Parent has_many kids
Kid belongs_to Parent.

Now I have view for say a new Parent. I also have provided an AJAX form
so that they can fill in all the children they have as well.

Whats the best way to go about adding a child to a parent at this stage.
Nothing has been committed to the database. And I can’t add a child to
the database without having a parent. But the parent has not been
created yet.

Thanks in advance for help! :slight_smile:

Take a look at ActiveRecord transactions.

If your params from the controller are :parent and :kids in your model
method you would do a transaction:

def self.create_family(params)
Parent.transaction do
parent = Parent.create(params[:parent])
params[:kids].each do |kid|
parent.kids.create(kid)
end
end
end

If one of the creates fails, they all get rolled back.

John.

On Jan 3, 9:47 pm, Luke G. [email protected]

Cheers for that, I think that’ll work.

Another question:
I have bunch of text_fields tags that get pushed onto the form via Ajax
every time the user hits “add new child” now, if I wanted to add 4 kids
to this family. Then I would have 4 text_fields.

Is it possible to group the text_fields in the view so that I can
iterate through them in the code-behind?

Have you seen the Railscast on this subject, I think it more or less
describes what you’re trying to achieve.

On 4 Jan, 03:54, Luke G. [email protected]

Thanks for sharing that wonderful resource. It looks exactly like the
thing I’m after!