Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sort Items fast with mysql and postgres queries on acts_as_list position column
module SortItemsExtension
def sort_items(ids)
unless ids.is_a?(Array)
raise ArgumentError, "ids isn't an array"
end
ids.map!(&:to_i)
old_ids = proxy_association.ids_reader
ids = ids - (ids - old_ids)
if old_ids.size != ids.size
raise ArgumentError, "Not all the ids were passed to sort! method"
end
scope = proxy_association.reflection.klass.where(id: ids)
if ActiveRecord::ConnectionAdapters::Mysql2Adapter
scope.update_all(['position = FIND_IN_SET(id, ?)', ids.join(',')])
elsif ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
scope.update_all(["position = STRPOS(?, ','||id||',')", ",#{ids.join(',')},"], id: ids)
end
end
end
has_many :photos, -> { extending(SortItemsExtension).order(:position) }, dependent: :destroy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.