When user clicks a specific item, I use jQuery's post method to update something in the database:
$.post("/posts/" + post_id + "/update_something",
{ some_param: some_value },
success_handler);
where update_something
looks like this:
def update_something
post = Post.find(params[:id])
post.update_attributes(:some_field => params[:some_param])
render :nothing => true
end
The problem is if update_attributes
fails, the request still succeeds and success_handler
is executed.
How could I cause the request to fail when update_attributes
fails such that success_handler
won't be executed?
Well, you have to add an error handler, and give it an error to handle. So, in your JavaScript:
And in Rails:
Note:
500
may or may not be the appropriate error code here—choose whichever among the 400s and 500s is appropriate.You can either do
render :status => 400
(or some other error code) in Rails, which will trigger theerror
callback of$.ajax()
, or you can render some JSON with an error message:render :json => { :success => false }
Then in your
success_handler
function you would:Edit:
Oh, and
update_attributes
returns false when it fails. So you can render your response based on that.Edit 2 years later:
After a couple years and seeing that this has a few upvotes, I'd highly recommend using the
status: 400
method instead of rendering200
. It's what theerror
handler in AJAX requests are for, and should be used that way.