# Nested Forms and ordering of new child elements

**URL:** <https://www.ruby-forum.com/t/nested-forms-and-ordering-of-new-child-elements/190348>\
**Category:** Rails\
**Created:** [June 18, 2010, 7:30am UTC](https://www.ruby-forum.com/t/nested-forms-and-ordering-of-new-child-elements/190348 "2010-06-18T07:30:31Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jens](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/d2c977/32.png) [@jens](https://www.ruby-forum.com/u/jens)\
**Post date:** [June 18, 2010, 7:30am UTC](https://www.ruby-forum.com/t/nested-forms-and-ordering-of-new-child-elements/190348/1 "2010-06-18T07:30:31Z")

</div>

Hi everybody,

I am using Rails 2.3 and the new “nested forms” concept to add child  
objects to a parent object from within a single form.

I have successfully gotten the example app from Github (alloy\_complex-  
form-examples) to run and modified the Javascript code (add\_child) to  
insert new child elements betwee existing children, _not_ only at the  
end of the list of children. This works fine, client-side.

However, this order is not preserved. When I try to save the form, the  
new children are simply appended to the list of children. Now I could  
solve this by populating a “position” attribute using Javascript. But  
when validation fails, the list of children is _also_ reordered before  
Rails re-renders the form, so that new children always appear at the  
end.

How do I define, within a form\_for / fields\_for construct, the ORDER  
of child elements so that it will be preserved

- upon re-rendering the form (when validations fail or exeptions  
occur)
- upon successfully saving the object

?

I have a “default\_scope :order =\> :position” set in the child model,  
which also works fine, but does not help in the first case.

How is the “accepts\_nested\_attributes\_for” implemented, can I somehow  
hook into this?

Thanks!

Jens
