Files
danbooru/app/models/comment_vote.rb
evazion 9efb374ae5 comments: allow swapping votes.
Allow users to upvote a comment, then downvote it, without raising an
error or having to manually remove the upvote first. The upvote is
automatically removed and replaced by the downvote.

Changes to the /comment_votes API:

* `POST /comment_votes` and `DELETE /comment_votes` now return a comment
  vote instead of a comment.
* The `score` param in `POST /comment_votes` is now 1 or -1, not
  `up` or `down.`
2021-01-21 07:58:50 -06:00

58 lines
1.3 KiB
Ruby

class CommentVote < ApplicationRecord
belongs_to :comment
belongs_to :user
validates_presence_of :score
validates_uniqueness_of :user_id, :scope => :comment_id, :message => "have already voted for this comment"
validate :validate_comment_can_be_down_voted
validates_inclusion_of :score, :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 validate_comment_can_be_down_voted
if is_positive? && comment.creator == CurrentUser.user
errors.add(:base, "You cannot upvote your own comments")
end
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