Skip to content

Instantly share code, notes, and snippets.

@arunthampi
Created January 19, 2012 06:00
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 arunthampi/1638263 to your computer and use it in GitHub Desktop.
Save arunthampi/1638263 to your computer and use it in GitHub Desktop.
Voting and ranking used in GitHeroes
def self.leaderboard
Hero.select("id, login, name, location, votes_received, avatar_url, html_url, rank() over(order by votes_received DESC)").limit(20)
end
def self.leaderboard_by_location(location)
Hero.select("id, login, name, location, votes_received, avatar_url, html_url, rank() OVER(PARTITION BY location ORDER BY votes_received DESC)").where("location = ?", location).limit(20)
end
Limit (cost=0.00..6.52 rows=20 width=227) (actual time=0.039..0.123 rows=20 loops=1)
-> WindowAgg (cost=0.00..157.07 rows=482 width=227) (actual time=0.037..0.116 rows=20 loops=1)
-> Index Scan Backward using desc_votes_recvd_idx on heros (cost=0.00..149.84 rows=482 width=227) (actual time=0.020..0.059 rows=20 loops=1)
Total runtime: 0.191 ms
(4 rows)
class Vote < ActiveRecord::Base
belongs_to :votee, :class_name => 'Hero', :counter_cache => :votes_received
belongs_to :voter, :class_name => 'Hero'
validates_presence_of :voter_id, :votee_id
validates_uniqueness_of :voter_id, :scope => :votee_id
validate :check_if_hero_votes_for_himself
def check_if_hero_votes_for_himself
errors.add(:votee_id, "You can't vote for yourself, unfortunately") if votee_id == voter_id
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment