Files
danbooru/app/controllers/post_votes_controller.rb
evazion d0c9f6e0b8 posts: allow toggling between upvotes and downvotes.
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`.
2021-01-29 02:22:23 -06:00

33 lines
981 B
Ruby

class PostVotesController < ApplicationController
skip_before_action :api_check
respond_to :js, :json, :xml, :html
def index
@post_votes = authorize PostVote.visible(CurrentUser.user).paginated_search(params, count_pages: true)
@post_votes = @post_votes.includes(:user, post: :uploader) if request.format.html?
respond_with(@post_votes)
end
def create
@post = Post.find(params[:post_id])
@post.with_lock do
@post_vote = authorize PostVote.new(post: @post, score: params[:score], user: CurrentUser.user)
PostVote.where(post: @post, user: CurrentUser.user).destroy_all
@post_vote.save
end
flash.now[:notice] = @post_vote.errors.full_messages.join("; ") if @post_vote.errors.present?
respond_with(@post_vote)
end
def destroy
@post = Post.find(params[:post_id])
@post_vote = @post.votes.find_by(user: CurrentUser.user)
authorize(@post_vote).destroy if @post_vote
respond_with(@post_vote)
end
end