作者:BigUncle | 来源:互联网 | 2023-01-12 12:17
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.
我在我的应用程序的页面上进行了就地编辑(使用Rails 2.3.5和jQuery)。我想知道更新失败时如何在页面上显示错误。
I'm using ajax (an XMLHttpRequest) to save an update to a Comment object. The controller has an update method like this:
我正在使用ajax(XMLHttpRequest)来保存对Comment对象的更新。控制器有一个像这样的更新方法:
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.
在Firebug中,我可以看到服务器返回“422”(相应的验证错误状态代码)。但它是对XMLHttpRequest的响应,因此没有重定向到错误页面。
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.
并触发一些迭代(并显示)任何错误的Javascript函数。
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?
我正在使用rails插件REST来实现就地编辑。它似乎没有任何回调函数来处理故障。我有什么选择?我可以编写一些Javascript来响应失败情况而不破解插件吗?我是否必须破解rest_in_place插件来处理故障情况?是否有更好的插件(对于Rails或jQuery)处理就地编辑,包括失败条件?
UPDATE
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?
来自Peter Bui标准JSON响应Rails和jQuery的这篇文章有助于展示如何使用XMLHttpRequest.status处理来自服务器的错误消息。我用ajax paydro-talks查看了他对博客的实现。我对处理简单错误条件所需的复杂性感到惊讶。通常Rails已经完成了所有的好处,但似乎JSON的服务器错误超出了范围。可以吗?
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.
我还查看了grimen的validatious-on-rails,当使用ajax XMLHttpRequest时,它适用于模型验证。我不清楚如何在验证成功时使用它来处理“保存”失败的一般情况。
1 个解决方案