0

I have two models, CheckIn and Consumer. The idea is that consumers can check in any number of times. I want to define a function in the Consumer model that allows me to return the top x_number of consumers who have the most CheckIns, sorted from highest to lowest number of CheckIns.

class Consumer < ActiveRecord::Base
  has_many :check_ins, dependent: :destroy

  def with_most_checkins( num_to_show )
    # ???
  end
end

class CheckIn < ActiveRecord::Base
  belongs_to :consumer
end
user3339471
  • 295
  • 2
  • 10

1 Answers1

0

Figured it out with the help of these posts:

Now I can get the top 3 consumers using:

Consumer.with_most_checkins(2)

With the use of scopes in the Consumer model class:

class Consumer < ActiveRecord::Base
  has_many :check_ins, dependent: :destroy
  has_many :promo_codes

  validates :email, :email => true

  scope :with_most_checkins, ->(num_to_show) {  select("consumers.*, count( check_ins.id ) AS check_ins_count").
      joins(:check_ins).
      group("consumers.id").
      order("check_ins_count DESC").
      limit(num_to_show) }

end
Community
  • 1
  • 1
user3339471
  • 295
  • 2
  • 10