post votes: fix error handling.

* Clean up javascript.
* Return HTTP 422 instead of HTTP 500 on "you have already voted for
  this post" errors.
* In json/xml error responses, return the error message in the `message`
  field, not `reason`.
* In json/xml success responses, return the post itself instead of a
  plain `{ success: true }` object.
This commit is contained in:
evazion
2019-08-13 21:30:20 -05:00
parent 00239c4901
commit f6b737103a
7 changed files with 11 additions and 40 deletions

View File

@@ -1,20 +1,20 @@
class PostVotesController < ApplicationController
before_action :voter_only
skip_before_action :api_check
respond_to :js, :json, :xml
rescue_with PostVote::Error, status: 422
def create
@post = Post.find(params[:post_id])
@post.vote!(params[:score])
rescue PostVote::Error, ActiveRecord::RecordInvalid => x
@error = x
render status: 500
respond_with(@post)
end
def destroy
@post = Post.find(params[:post_id])
@post.unvote!
rescue PostVote::Error => x
@error = x
render status: 500
respond_with(@post)
end
end