Reputation: 2076
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..
Upvotes: 1
Views: 1795
Reputation: 9712
I am presuming that ordering
is 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 by ordering ASC
uses the database, and since it's not saved it doesn't get sorted.
Try this instead:
<%= f.fields_for :children, @parent.children.sort_by(&:ordering) do |ff| %>
This will use ordering
stored in memory, which should be what was previously submitted by the form.
Upvotes: 5
Reputation: 21884
I'm really not sure, but try:
In the controller
@children = @parent.children.reorder("ordering ASC")
In the view
<%= f.fields_for :children, @children do |ff| %>
<%= render "child_fields", :ff => ff %>
<% end %>
Upvotes: 0