Skip to content

Commit

Permalink
Merge pull request #12 from Hopebaytech/master
Browse files Browse the repository at this point in the history
User can undo vote by clicking same button again
  • Loading branch information
jongha committed Aug 19, 2015
2 parents 9853e6e + a0d1165 commit 00744e4
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions app/models/votes.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
class Votes < ActiveRecord::Base
unloadable

def add_vote(message_id, user_id, point = 0)
votes = Votes.where('message_id = %d and user_id = %d' % [message_id, user_id]).limit(1)
def add_vote(message_id, user_id, point = "0")
votes = Votes.where('message_id = %d and user_id = %d' % [message_id, user_id]).first

unless votes.count == 0
votes.point = point.nil? ? 0 : point
point = point.to_i
if votes
votes.point = (votes.point == point)? 0 : point
votes.save!
else
votes = Votes.new
votes.message_id = message_id
votes.user_id = user_id
votes.point = point.nil? ? 0 : point
votes.point = point
votes.save!
end

Expand All @@ -27,7 +28,7 @@ def get_points(user_id, message_id)
"plus" => Votes.where('message_id = %d and point > 0' % message_id).sum(:point),
"minus" => Votes.where('message_id = %d and point < 0' % message_id).sum(:point),
"zero" => Votes.where('message_id = %d and point = 0' % message_id).sum(:point),
"vote" => Votes.where('message_id = %d and user_id = %d' % [message_id, user_id]).count(:point),
"vote" => Votes.where('message_id = %d and user_id = %d' % [message_id, user_id]).sum(:point),
}
end
end

0 comments on commit 00744e4

Please sign in to comment.