forked from AdaGold/media-ranker-revisited
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathwork.rb
52 lines (42 loc) · 1.22 KB
/
work.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Work < ApplicationRecord
CATEGORIES = %w(album book movie)
has_many :votes, dependent: :destroy
has_many :ranking_users, through: :votes, source: :user
validates :category, presence: true,
inclusion: { in: CATEGORIES }
validates :title, presence: true,
uniqueness: { scope: :category }
# This is called a model filter, and is very similar to a controller filter.
# We want to fixup the category *before* we validate, because
# our validations are rather strict about what's OK.
before_validation :fix_category
def self.to_category_hash
data = {}
CATEGORIES.each do |cat|
data[cat] = by_category(cat)
end
return data
end
def self.by_category(category)
category = category.to_s.singularize.downcase
self.where(category: category).order(vote_count: :desc)
end
def self.best_albums
top_ten("album")
end
def self.best_books
top_ten("book")
end
def self.best_movies
top_ten("movie")
end
def self.top_ten(category)
where(category: category).order(vote_count: :desc).limit(10)
end
private
def fix_category
if self.category
self.category = self.category.downcase.singularize
end
end
end