Like 9efb374ae, allow users to toggle between upvoting and downvoting a
post without raising an error or having to manually remove the vote
first. If you upvote a post, then downvote it, the upvote is
automatically removed and replaced by the downvote.
Other changes:
* Tagging a post with `upvote:self` or `downvote:self` is now silently
ignored when the user doesn't have permission to vote, instead of
raising an error.
* Undoing a vote that doesn't exist now does nothing instead of
returning an error. This can happen if you open the same post in two
tabs, undo the vote in tab 1, then try to undo the vote again in tab 2.
Changes to the /post_votes API:
* `POST /post_votes` and `DELETE /post_votes` now return a post vote
instead of a post.
* The `score` param in `POST /post_votes` is now 1 or -1, not `up` or
`down`.
50 lines
1.0 KiB
Ruby
50 lines
1.0 KiB
Ruby
class CommentVote < ApplicationRecord
|
|
belongs_to :comment
|
|
belongs_to :user
|
|
|
|
validates :user_id, uniqueness: { scope: :comment_id, message: "have already voted for this comment" }
|
|
validates :score, inclusion: { in: [-1, 1], message: "must be 1 or -1" }
|
|
|
|
after_create :update_score_after_create
|
|
after_destroy :update_score_after_destroy
|
|
|
|
def self.visible(user)
|
|
if user.is_moderator?
|
|
all
|
|
elsif user.is_anonymous?
|
|
none
|
|
else
|
|
where(user: user)
|
|
end
|
|
end
|
|
|
|
def self.search(params)
|
|
q = search_attributes(params, :id, :created_at, :updated_at, :score, :comment, :user)
|
|
q.apply_default_order(params)
|
|
end
|
|
|
|
def is_positive?
|
|
score == 1
|
|
end
|
|
|
|
def is_negative?
|
|
score == -1
|
|
end
|
|
|
|
def update_score_after_create
|
|
comment.with_lock do
|
|
comment.update_columns(score: comment.score + score)
|
|
end
|
|
end
|
|
|
|
def update_score_after_destroy
|
|
comment.with_lock do
|
|
comment.update_columns(score: comment.score - score)
|
|
end
|
|
end
|
|
|
|
def self.available_includes
|
|
[:comment, :user]
|
|
end
|
|
end
|