在我的控制器创建方法中,我创建了一个父级&使用accepts_nested_attributes的子(ren)对象。一切正常。
子项具有正确设置的排序属性。
但是,当验证失败时(对于缺少的属性说),当fields_for方法运行时,子对象的顺序不保留。
我尝试过使用parent.children.reorder(“订购ASC”),但这不起作用......
如果能让事情变得更清楚,我很乐意发布任何代码!
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
,格式为
<%= f.fields_for :children do |ff| %>
<%= render "child_fields", :ff => ff %>
<% end %>
任何指针都会很棒..
答案 0 :(得分:5)
我假设你的表单中正在设置ordering
,问题是当保存失败时它不会生效。原因似乎是按ordering ASC
排序使用数据库,因为它没有保存,所以它不会被排序。
请改为尝试:
<%= f.fields_for :children, @parent.children.sort_by(&:ordering) do |ff| %>
这将使用存储在内存中的ordering
,这应该是以前由表单提交的内容。
答案 1 :(得分:0)
我真的不确定,但请尝试:
在控制器中
@children = @parent.children.reorder("ordering ASC")
在视图中
<%= f.fields_for :children, @children do |ff| %>
<%= render "child_fields", :ff => ff %>
<% end %>