Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Created May 10, 2020 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inopinatus/3d7788a858d90b1ed9c323b7712f6f06 to your computer and use it in GitHub Desktop.
Save inopinatus/3d7788a858d90b1ed9c323b7712f6f06 to your computer and use it in GitHub Desktop.
By Most
module ByMost
extend ActiveSupport::Concern
included do
scope :by_most, ->(assoc) {
reflection = reflect_on_association(assoc)
left_joins(assoc)
.group(primary_key)
.order(reflection.klass.arel_table[reflection.foreign_key].count.desc)
}
end
end
@inopinatus
Copy link
Author

class User
  include ByMost
  has_many :votes
  has_many :friends

User.by_most(:votes)
User.by_most(:friends)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment