Reputation: 5002
I have a game with a Rails 4 + Postgres backend on Heroku. Our daily leaderboard shows the highest 100 scores in the game. We have a User model and a Score model (User has_many :scores).
It works as expected like this:
class Score < ActiveRecord::Base
belongs_to :user
def self.daily_leaders
where(['created_at > ? and created_at < ?', Time.now.beginning_of_day, Time.now.end_of_day]).order("points DESC").limit(100)
end
end
But we'd now like to change this so it only shows the highest score for each user. I have tried every combination of additional .select() .distinct and .pluck ActiveRecord methods I can, but I'm always getting PG errors.
What would be the proper way to get JUST each user's highest score for just today?
Upvotes: 0
Views: 349
Reputation: 29359
class Score < ActiveRecord::Base
belongs_to :user
def self.user_max_scores
where('date(created_at) = ?', Date.today).select('user_id, max(points) as max_points').group(:user_id)
end
end
Upvotes: 2