How to fail Ajax request in Rails?

前端 未结 2 867
盖世英雄少女心
盖世英雄少女心 2021-02-07 21:08

When user clicks a specific item, I use jQuery\'s post method to update something in the database:

$.post(\"/posts/\" + post_id + \"/update_something\", 
                


        
2条回答
  •  一生所求
    2021-02-07 21:32

    You can either do render :status => 400 (or some other error code) in Rails, which will trigger the error 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:

    function success_handler (response) {
        if (response.success) {
            // do stuff
        }
    }
    

    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 rendering 200. It's what the error handler in AJAX requests are for, and should be used that way.

提交回复
热议问题