Skip to content

Instantly share code, notes, and snippets.

@dmitry
Created December 8, 2012 17:18
Show Gist options
  • Save dmitry/4241080 to your computer and use it in GitHub Desktop.
Save dmitry/4241080 to your computer and use it in GitHub Desktop.
Sort photos in Rails using FIND_IN_SET MySQL function
# 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