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.
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.
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?