Skip to content

Instantly share code, notes, and snippets.

@dmitry
Last active June 15, 2017 21:39
Show Gist options
  • Save dmitry/909749b659a29d6e244f744d1806513c to your computer and use it in GitHub Desktop.
Save dmitry/909749b659a29d6e244f744d1806513c to your computer and use it in GitHub Desktop.
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