Skip to content

Commit

Permalink
Undo vote by clicking same button
Browse files Browse the repository at this point in the history
... as same as stackoverflow
  • Loading branch information
Jethro Yu committed Jul 6, 2015
1 parent 9853e6e commit a0d1165
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 a0d1165

Please sign in to comment.