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}
or maybe this:
format.json {render :json => { :status => :error, :message => "Could not be saved" }.to_json, :status => 400 }
and trigger some Javascript function that iterates through (and displays) any errors.
I'm using a rails plugin 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?
UPDATE
This post from Peter Bui Standard JSON Response for Rails and jQuery was helpful in showing how to handle an error message from the server using XMLHttpRequest.status
. I looked at his implementation of a blog using ajax paydro-talks. I'm surprised at the complexity required to handle a simple error condition. Usually Rails has all the goodness baked in but it seems server errors with JSON are out of scope. Can that be?
I also looked at grimen's validatious-on-rails which accommodates models validations when ajax XMLHttpRequest is used. It's not clear to me how I'd use it to handle the general case of a "save" failing when validations succeed.
P.S.
Please vote me up... so I can use more than one HTML link when I ask my question :-)