Skip to content

Instantly share code, notes, and snippets.

@xuncheng
Last active September 15, 2015 16:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save xuncheng/5328c1548a6515f09a1a to your computer and use it in GitHub Desktop.
# select mysql records in an arbitrary order
# http://www.justinweiss.com/blog/2015/04/20/how-to-select-database-records-in-an-arbitrary-order/
module Extensions::ActiveRecord::FindByOrderedFields
extend ActiveSupport::Concern
module ClassMethods
def find_ordered_by(field, values)
sanitized_field_string = values.present? ? values.map {|v| connection.quote(v)}.join(",") : "''"
where(field => values).order("FIELD(#{field}, #{sanitized_field_string})")
end
end
end
ActiveRecord::Base.send(:include, Extensions::ActiveRecord::FindByOrderedFields)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment