Given the following models:
team.rb
class Team < ActiveRecord::Base
has_many :events, :dependent => :destroy
has_many :challenges, :through => :events
validates :name, :presence => true, :uniqueness => true
end
challenge.rb
class Challenge < ActiveRecord::Base
has_many :events, :dependent => :destroy
has_many :teams, :through => :events
validates :name, :presence => true, :uniqueness => true
validates :flag, :presence => true, :uniqueness => true
end
event.rb
class Event < ActiveRecord::Base
belongs_to :team
belongs_to :challenge
validates :team, :presence => true
validates :challenge, :presence => true
end
I want to display the teams with the highest “rank”.
Where the highest ranking team has the most challenges completed (events).
If there is a tie at X events then the team that completed the Xth event
first has the highest rank.
So I can easily sort the teams based on the number of events and then show them.
Like so:
def index
@teams = Team.includes(:events).
select("*, COUNT(events.id)").
group("teams.id, events.id").
order("COUNT(events.id) DESC")
end
However I don’t know how to handle the case where there is a tie.
Does anybody know a good way of doing this with SQL?
I would rather use SQL to do this versus performing an extra step
on the app server.
Thanks!!
So I got it working.
Thanks xnm. You sent me in the right direction. Can’t believe I forgot about MAX. 🙁
I also had to fix my GROUP BY…
Here is the working version: