From 2a7a19c93ee0e0d77e4e388d43f36a721c7ab715 Mon Sep 17 00:00:00 2001 From: Star Rauchenberger Date: Fri, 20 Oct 2023 21:27:06 -0400 Subject: Added post voting --- app/models/concerns/votable.rb | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 app/models/concerns/votable.rb (limited to 'app/models/concerns') 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 @@ +module Votable + extend ActiveSupport::Concern + + included do + has_many :votes, as: :votable + + def already_upvoted?(ip) + !votes.where(ip: ip, upvote: 1).empty? + end + + def already_downvoted?(ip) + !votes.where(ip: ip, upvote: 0).empty? + end + + def upvote!(ip) + return false if already_upvoted?(ip) + + if already_downvoted?(ip) + votes.where(ip: ip, upvote: 0).first.delete + self.downvotes -= 1 + save! + else + votes.create(ip: ip, upvote: 1).save + self.upvotes += 1 + save! + end + end + + def downvote!(ip) + return false if already_downvoted?(ip) + + if already_upvoted?(ip) + votes.where(ip: ip, upvote: 1).first.delete + self.upvotes -= 1 + save! + else + votes.create(ip: ip, upvote: 0).save + self.downvotes += 1 + save! + end + end + end +end -- cgit 1.4.1