diff options
author | Star Rauchenberger <fefferburbia@gmail.com> | 2023-10-20 21:27:06 -0400 |
---|---|---|
committer | Star Rauchenberger <fefferburbia@gmail.com> | 2023-10-20 21:27:06 -0400 |
commit | 2a7a19c93ee0e0d77e4e388d43f36a721c7ab715 (patch) | |
tree | c5e775bca4600d111d01d1bd7998d3b6252462e6 /app/models | |
parent | 74b1612e49ebd9cb29efb85f3afeb07f0e8d608a (diff) | |
download | thoughts-2a7a19c93ee0e0d77e4e388d43f36a721c7ab715.tar.gz thoughts-2a7a19c93ee0e0d77e4e388d43f36a721c7ab715.tar.bz2 thoughts-2a7a19c93ee0e0d77e4e388d43f36a721c7ab715.zip |
Added post voting
Diffstat (limited to 'app/models')
-rw-r--r-- | app/models/blog.rb | 1 | ||||
-rw-r--r-- | app/models/concerns/votable.rb | 43 | ||||
-rw-r--r-- | app/models/vote.rb | 6 |
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 @@ | |||
1 | class Blog < ApplicationRecord | 1 | class 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 @@ | |||
1 | module 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 | ||
43 | end | ||
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 @@ | |||
1 | class Vote < ApplicationRecord | ||
2 | belongs_to :votable, polymorphic: true | ||
3 | |||
4 | validates :upvote, presence: true, inclusion: { in: [0, 1] } | ||
5 | validates :ip, presence: true | ||
6 | end | ||