Took too long to edit to correct my mistake. The code in the form above only works when the moved item is moved up. This is the hastily corrected version which is in need of some refactoring:
It is actually possible to do all updates in a single query, preferably using the fact that your model is using acts_as_list:
ruby
defsort
ids = params[:faq].map { |id| id.to_i }
item = first_moved_item(ids)
item.insert_at(moved_to(ids,item)) # Using acts_as_listenddeffirst_moved_item ids
ids.each_with_index do |id, i|
returnFaq.find(originals[i]) if originals[i] != id
endenddefmoved_to ids, item
ids.index(item.id) + 1enddeforiginals@originals ||= Faq.where(id: params[:faq]).order(:position).pluck(:id)
end
This makes use of the fact that the insert_at method already has the logic to optimally execute the move in the most efficient fashion. For me this is more than an order of magnitude faster since I was using sorted on a list that could contain upwards of 500 items.
Took too long to edit to correct my mistake. The code in the form above only works when the moved item is moved up. This is the hastily corrected version which is in need of some refactoring:
It is actually possible to do all updates in a single query, preferably using the fact that your model is using acts_as_list:
This makes use of the fact that the insert_at method already has the logic to optimally execute the move in the most efficient fashion. For me this is more than an order of magnitude faster since I was using sorted on a list that could contain upwards of 500 items.