Skip to content

Instantly share code, notes, and snippets.

@xuncheng xuncheng/gist:5328c1548a6515f09a1a Secret
Last active Sep 15, 2015

Embed
What would you like to do?
# 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
You can’t perform that action at this time.