Rails的AJAX响应成功/失败

时间:2014-06-02 22:22:18

标签: jquery ruby-on-rails ajax

我有以下控制器方法:

def update
    approval = Approval.where(user: current_user, id: params[:id])
    if approval.update_attributes(approved: params[:approved) 
       #success
    else
       #fail
    end
    respond_to do |format|
      format.js { render :nothing => true }
    end
end

如何设置从Rails发送成功或失败到我的AJAX呼叫?

1 个答案:

答案 0 :(得分:0)

在导轨部分,您可以这样做:

def update
    approval = Approval.where(user: current_user, id: params[:id])
    if approval.update_attributes(approved: params[:approved]) 
      render nothing: true, status: ok
    else
      render nothing: true, status: 
    end
end

在JSON部分,如上所述here

$.ajax(serverUrl, {
   statusCode: {
      200: function (response) {
        // whatever
      },
      500: function (response) {
        // whatever
      }
   }
});