Created
December 8, 2012 17:18
-
-
Save dmitry/4241080 to your computer and use it in GitHub Desktop.
Sort photos in Rails using FIND_IN_SET MySQL function
This file contains 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
# TODO can be optimized to use custom class and `model_ids` method | |
module SortPhotos | |
def sort_photos!(ids) | |
raise ArgumentError, "ids isn't an array" if !ids.is_a?(Array) | |
ids.map!(&:to_i) | |
old_ids = self.photo_ids | |
ids = ids - (ids - old_ids) | |
raise ArgumentError, "Not all the ids were passed to sort! method" if old_ids.size != ids.size | |
reflections[:photos].klass.update_all(['position = FIND_IN_SET(id, ?)', ids.join(',')], {:id => ids}) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment