在 Rails 中的同一操作中响应和重定向 [英] Respond_to and redirect in the same action in Rails
问题描述
在 Rails 控制器的更新操作中,通常有如下代码:
In the Update action of Rails controllers usually there is code that looks like this:
def update
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
redirect_to(@book)
else
render :edit
end
end
在其他情况下,这将呈现编辑模板.但是,如果我想使用 response_to 怎么办,与我在编辑操作中的方式完全相同,如:
In the else case, this will render the edit template. But what if I wanted to use a respond_to, exactly the same way that I have in the edit action, as:
def update
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
redirect_to(@book)
else
respond_to do |format|
format.html # edit.html.erb
format.json { render :json => @team }
end
end
end
因此,如果更新失败,请确保根据请求的格式返回 json 或 html.这有意义吗?如果是这样,您将如何避免错误:在此操作中多次调用渲染和/或重定向"
So, if the Update fails, be sure you are returning a json or html depending on the requested format. Does that makes sense? If so, how would you avoid the error: "Render and/or redirect were called multiple times in this action"
推荐答案
对我来说很有意义.答案应该很简单,只需在 redirect_to
之后 return
.
Makes sense to me. The answer should be simple, just return
after redirect_to
.
def update
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
redirect_to(@book)
return
else
respond_to do |format|
format.html # edit.html.erb
format.json { render :json => @team }
end
end
end
不确定你是如何多次渲染的,但假设你是这样,一个位置良好的 return
应该告诉 RAILS 在重定向后停止处理任何进一步的渲染.如果这一切都是真的,很可能是 after_filter
从某处干扰了.
Not sure exactly how you're rendering multiple times, but assuming you are, a well-placed return
should tell RAILS to stop processing any further renders after redirecting. If that's all true, it's likely that there's an after_filter
interfering from somewhere.
这篇关于在 Rails 中的同一操作中响应和重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!