/gist:5328c1548a6515f09a1a Secret
Last active
September 15, 2015 16:09
Star
You must be signed in to star a gist
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
# 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