Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

inopinatus commented May 10, 2020

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