about summary refs log tree commit diff stats
path: root/app/models
diff options
context:
space:
mode:
Diffstat (limited to 'app/models')
-rw-r--r--app/models/blog.rb1
-rw-r--r--app/models/concerns/votable.rb43
-rw-r--r--app/models/vote.rb6
3 files changed, 50 insertions, 0 deletions
diff --git a/app/models/blog.rb b/app/models/blog.rb index 6db75ec..03643bf 100644 --- a/app/models/blog.rb +++ b/app/models/blog.rb
@@ -1,5 +1,6 @@
1class Blog < ApplicationRecord 1class Blog < ApplicationRecord
2 include Recordable 2 include Recordable
3 include Votable
3 4
4 acts_as_taggable 5 acts_as_taggable
5 6
diff --git a/app/models/concerns/votable.rb b/app/models/concerns/votable.rb new file mode 100644 index 0000000..ba6e6d5 --- /dev/null +++ b/app/models/concerns/votable.rb
@@ -0,0 +1,43 @@
1module Votable
2 extend ActiveSupport::Concern
3
4 included do
5 has_many :votes, as: :votable
6
7 def already_upvoted?(ip)
8 !votes.where(ip: ip, upvote: 1).empty?
9 end
10
11 def already_downvoted?(ip)
12 !votes.where(ip: ip, upvote: 0).empty?
13 end
14
15 def upvote!(ip)
16 return false if already_upvoted?(ip)
17
18 if already_downvoted?(ip)
19 votes.where(ip: ip, upvote: 0).first.delete
20 self.downvotes -= 1
21 save!
22 else
23 votes.create(ip: ip, upvote: 1).save
24 self.upvotes += 1
25 save!
26 end
27 end
28
29 def downvote!(ip)
30 return false if already_downvoted?(ip)
31
32 if already_upvoted?(ip)
33 votes.where(ip: ip, upvote: 1).first.delete
34 self.upvotes -= 1
35 save!
36 else
37 votes.create(ip: ip, upvote: 0).save
38 self.downvotes += 1
39 save!
40 end
41 end
42 end
43end
diff --git a/app/models/vote.rb b/app/models/vote.rb new file mode 100644 index 0000000..e2d8386 --- /dev/null +++ b/app/models/vote.rb
@@ -0,0 +1,6 @@
1class Vote < ApplicationRecord
2 belongs_to :votable, polymorphic: true
3
4 validates :upvote, presence: true, inclusion: { in: [0, 1] }
5 validates :ip, presence: true
6end