I have a controller action which looks like so –
def upvote
@post = Post.find(params[:id])
if user_has_rated_post?
# I want to interrupt AJAX here
redirect_to[:forum, @post.question], :notice => "You already voted for this post"
else
@post.upvote
add_rating_to_post(1, @post)
@post.save
redirect_to[:forum, @post.question], :notice => "Post Up Voted"
end
end
and I have an AJAX call to up vote a post, which works perfectly fine except I need it to stop the AJAX call if the first condition, user_has_rated_post? is met.
So the question is how can I interrupt or force an error to return to AJAX, or should I be trying to go about this another way?
Yes you have to return something that jQuery(or your AJAX solution) interprets as an error. Then you will have to handle this error in javascript code(or just do nothing if that fits). I think anything above 400 is by convention considered an error. See the list of HTTP status codes and pick the one that suits you most http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. Here I would bet on 403 – The server understood the request, but is refusing to fulfill it. You can always just render 500, but I think it’s better to be specific.