In my controllers create method I am creating a parent & child(ren) objects using accepts_nested_attributes. That all works fine.
The children have an ordering attribute which is correctly set.
However, when the validation fails (for a missing attribute say) the ordering of the child objects is not preserved when the fields_for method runs.
I have tried using parent.children.reorder("ordering ASC") but that doesn't work...
I'm happy to post any code should it make things clearer!
def create
@parent = Parent.new(params[:parent])
respond_to do |format|
if @parent.save
format.html
else
@parent.children.reorder("ordering ASC") #this makes no difference
format.html { render :action => "new" }
end
end
end
and in the form partial
<%= f.fields_for :children do |ff| %>
<%= render "child_fields", :ff => ff %>
<% end %>
Any pointers would be great..
I am presuming that
orderingis being set in your form, and the problem is that it is not taking effect when save fails. The reason for that appears to be that by sorting byordering ASCuses the database, and since it's not saved it doesn't get sorted.Try this instead:
This will use
orderingstored in memory, which should be what was previously submitted by the form.