Last active
June 15, 2017 21:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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