0

I have the following controller method:

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

How do I manage to send a success or fail from Rails to my AJAX call?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296
  • Doesn't the `renter status: status_code` work for you? [http status](http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option) – Tamer Shlash Jun 02 '14 at 22:27
  • Well, what status should I use if update_attributes fail? – Hommer Smith Jun 02 '14 at 22:32
  • 500 is generic application/server error. (See http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error) I would add that HTTP status codes aren't supposed to represent your application's logic. There is no "database error" code because web servers aren't responsible for databases or other application logic. It'd be better to return a JSON object representing your error if you need to operate on the status code client side. – David Elner Jun 02 '14 at 22:40
  • Why should if fail? the response depends on the reason. That might complicate your app though, If you're not exposing a public API for use by others, just pick a `5xx` or `4xx` (again depends on the reason) error that you find suitable from the table in the previous link. – Tamer Shlash Jun 02 '14 at 22:43
  • David Elner, how do I make a conditional render of a JSON? If I try to do a conditional, I keep getting ``Render and/or redirect were called multiple times `` – Hommer Smith Jun 02 '14 at 22:46

1 Answers1

0

On the rails part, you can do it like so:

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

On the JSON Part, as mentioned here:

$.ajax(serverUrl, {
   statusCode: {
      200: function (response) {
        // whatever
      },
      500: function (response) {
        // whatever
      }
   }
});
Community
  • 1
  • 1
Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82