Keeping custom sorting across edit/update controller methods

# I have an order class Order < ActiveRecord::Base   has_many :order_items end # with items class OrderItem < ActiveRecord::Base   belongs_to :family   belongs_to :order   has_many :order_items

# I sort the order items via a scope which joins with item family to sort them accordingly   scope :default_order, joins(:family).order('families.name, order_items.quantity') end

# Controller def edit    @order = Order.find params[:id]    @ois = @order.order_items.default_order end

# My problem is in the update method, if we have errors and must show the order to the user... # How do I sort properly my items? def update     ...     if @order.update_attributes(params[:order])        ...     else #it doesn't validate        #if I do        @ois = @order.order_items.default_order       # items are reloaded (with the correct order) BUT user input and validation errors are lost.     end end

How do I keep the sorting + data?!? - I don't want to use a default_scope in order items because of problems I had with it in the past and performance. - Since my sorting is made over two models, I can't use the basic :order on the has_many association. I guess the best would be to be able to assign a default_scope on the has_many association so when they are loaded implicitly (especially during @order.update_attributes(params[:order]) the order is consistent.

To show the pain and ugliness, I currently do this way. @items = @order.order_items @items = params[:order][:order_items_attributes].values.map{|v| v[:id]}.map{|id| @items.detect{|i| i.id == id.to_i}} unless @items.empty? It works because the params hash keeps the sorting order....

I really hope I'm doing something wrong and there is a better way...