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/concerns | |
parent | 74b1612e49ebd9cb29efb85f3afeb07f0e8d608a (diff) | |
download | thoughts-2a7a19c93ee0e0d77e4e388d43f36a721c7ab715.tar.gz thoughts-2a7a19c93ee0e0d77e4e388d43f36a721c7ab715.tar.bz2 thoughts-2a7a19c93ee0e0d77e4e388d43f36a721c7ab715.zip |
Added post voting
Diffstat (limited to 'app/models/concerns')
-rw-r--r-- | app/models/concerns/votable.rb | 43 |
1 files changed, 43 insertions, 0 deletions
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 | ||