如何进行渲染 :edit 调用在地址栏中显示/edit [英] How to make a render :edit call show the /edit in the address bar
问题描述
在我的 Rails 应用程序中我的首选项控制器的更新操作中,如果验证/保存等中有任何错误,则会调用:
In the update action of my preferences controller in my Rails app, if there are any errors in the validation/save etc there's a call to:
<代码>format.html { 渲染:编辑}
没有什么特别的 - 但是,当点击此代码时,浏览器中的地址会发生变化并丢失 URL 中的/edit.
Nothing too unusual there - however, when this code is hit, the address in the browser changes and loses the /edit in the URL.
例如:
首先,我的浏览器显示我在以下地址的页面上:http://localhost:3000/preferences/1/edit
To start with, my browser shows I am on the page at following address: http://localhost:3000/preferences/1/edit
但是,一旦检测到错误并调用渲染器,其中的地址就会更改为 http://本地主机:3000/preferences/1
However, once the errors are detected and the render is called the address in the is changed to http://localhost:3000/preferences/1
我不能说我以前曾经注意到这种行为 - 但是有没有办法强制/edit 留在 URL 的末尾?没有/edit 它有效地显示了显示页面的 URL(我没有模板!)
I can't say I've ever noticed this behaviour before - but Is there a way to force the /edit to stay on the end of the URL? Without the /edit it is effectively showing the URL of the show page (and I don't have a template for that!)
非常感谢,灰
推荐答案
你可以redirect_to
编辑页面,而不是调用render
,并使用flash
跟踪模型:
Instead of calling render
, you can redirect_to
the edit page, and use flash
to keep track of the model:
def update
# ...
if !@model.save # there was an error!
flash[:model] = @model
redirect_to :action => :edit
end
end
然后在 edit
操作中,您可以从 flash[:model]
重新加载值,即:
And then in the edit
action you can reload the values from flash[:model]
, ie:
def edit
if flash[:model]
@model = flash[:model]
else
@model = ... # load model normally
end
end
更新:
正如下面评论的那样,我认为当我写这个答案时,我试图提供一种方法来更新 URL(需要重定向)并保留模型的更改属性,这就是模型存储在闪存中的原因.然而,将模型粘贴到闪存中是一个非常糟糕的主意(在 Rails 的更高版本中,它无论如何都会被反序列化),并且 RESTful 路由并不真正需要使 URL 包含 edit
.
通常的模式是仅使用内存中已有的模型渲染编辑操作,而放弃拥有理想"网址:
The usual pattern would be to just render the edit action with the model already in memory, and forego having the "ideal" URL:
def update
# Assign attributes to the model from form params
if @model.save
redirect_to action: :index
else
render :edit
end
end
或者,如果最好使用理想"URL 并且您不关心维护验证失败的已更改属性,请参阅@jamesmarkcook 的回答.
Alternately, if it's preferable to have the "ideal" URL and you don't care about maintaining changed attributes that failed validation, see @jamesmarkcook's answer.
这篇关于如何进行渲染 :edit 调用在地址栏中显示/edit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!