Rails 3 fields_for - sort order gets lost

怎甘沉沦 提交于 2019-12-04 09:06:56

问题


I am using Rails 3.0.3 with ruby 1.9.2p0.

In my profiles_controller (edit function) I have this call

@profile = Profile.find(params[:id])
@profile_items = @profile.profile_items.order("pos")

to get the @profile_items in the correct order, sorted on "pos". In the _form.html.erb I have the following

<% @profile_items.each do |pi| %>
  <%= pi.pos %> | 
<% end %>
<%= f.fields_for :profile_items do |f2| %>
  <%= render 'profile_item_fields', :f => f2 %>
<% end %>

The 3 first lines are test code to show that the @profile_items are in the correct order. But when they are rendered they have lost the sorted order!

Now I have search a lot for an answer and I think this must be a common "trap" to fall into.

Thankful for any help...


回答1:


According to the Rails Documentation for fields_for, you can also specify the record object after the record name.

So something like this should work...

<%= f.fields_for :profile_items, @profile_items do |f2| %>
  <%= render 'profile_item_fields', :f => f2 %>
<% end %>



回答2:


This can be accomplished with a default_scope on the nested model:

class YourModel < ActiveRecord::Base
  belongs_to :other_model
  default_scope { order(:name) }
end


来源:https://stackoverflow.com/questions/4961832/rails-3-fields-for-sort-order-gets-lost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!