How to show errors using JSON when an update fails in Rails 2.3.5 with jQuery

Posted by Fortuity on Stack Overflow See other posts from Stack Overflow or by Fortuity
Published on 2010-03-22T01:34:57Z Indexed on 2010/03/22 1:41 UTC
Read the original article Hit count: 476

Filed under:
|
|
|
|

I've got in-place editing on a page in my app (using Rails 2.3.5 and jQuery). I want to know how to display an error on the page when the update fails.

I'm using ajax (an XMLHttpRequest) to save an update to a Comment object. The controller has an update method like this:

def update
  @comment = Comment.find(params[:id])
  respond_to do |format|
    # if @comment.update_attributes!(params[:comment])
    if false #deliberately forcing a fail here to see what happens
      format.json { render :nothing =>  true }
    else
      format.json { render :json => @comment.errors, :status => :unprocessable_entity }
    end
  end
end

In Firebug, I can see the server returns a "422" (an appropriate validation error status code). But it's a response to an XMLHttpRequest so there is no redirect to an error page.

I think I actually want to do this:

format.json { render :json => @comment.errors}

and trigger some Javascript function that iterates through (and displays) any errors.

I'm using a rails plugin http://github.com/janv/rest_in_place/ to implement the in-place editing. It doesn't appear to have any callback function to handle a failure. What are my options? Can I write some Javascript to respond to a failure condition without hacking the plugin? Do I have to hack the rest_in_place plugin to handle a failure condition? Is there a better plugin (for Rails or jQuery) that handles in-place editing, including failure conditions?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about JavaScript