How to fail Ajax request in Rails?

前端 未结 2 895
盖世英雄少女心
盖世英雄少女心 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:14

    Well, you have to add an error handler, and give it an error to handle. So, in your JavaScript:

    $.post( "/posts/" + post_id + "/update_something",
            { some_param : some_value }
          )
      .done( successHandler )
      .fail( errorHandler )      // define errorHandler somewhere, obviously
    ;
    

    And in Rails:

    def update_something
      post    = Post.find params[ :id ]
    
      success = post.update_attributes :some_field => params[ :some_param ]
    
      head success ? :ok : :internal_server_error
    end
    

    Note: 500 may or may not be the appropriate error code here—choose whichever among the 400s and 500s is appropriate.

提交回复
热议问题