在我的 Rails 应用程序中我的首选项 Controller 的更新操作中,如果验证/保存等中有任何错误,则调用:
format.html { render :edit }
那里没有什么太不寻常的地方——但是,当这个代码被点击时,浏览器中的地址会改变并丢失 URL 中的/edit。
例如:
首先,我的浏览器显示我在以下地址的页面上:http://localhost:3000/preferences/1/edit
但是,一旦检测到错误并调用渲染,地址将更改为 http://localhost:3000/preferences/1
我不能说我以前曾经注意到过这种行为 - 但是有没有办法强制/edit 留在 URL 的末尾?没有/edit 它有效地显示了显示页面的 URL(而且我没有模板!)
非常感谢,
灰
最佳答案
而不是调用 render
, 你可以 redirect_to
编辑页面,并使用 flash
跟踪模型:
def update
# ...
if !@model.save # there was an error!
flash[:model] = @model
redirect_to :action => :edit
end
end
然后在
edit
您可以从 flash[:model]
重新加载值的操作, IE:def edit
if flash[:model]
@model = flash[:model]
else
@model = ... # load model normally
end
end
更新:
正如下面评论的那样,我认为当我写这个答案时,我试图提供一种方法来更新 URL(这需要重定向)并保留模型的更改属性,这就是模型存储在闪存中的原因。但是,将模型粘贴到 flash 中是一个非常糟糕的主意(在以后的 Rails 版本中,无论如何它只会被反序列化),并且 RESTful 路由实际上并不需要使 URL 包含
edit
。 .通常的模式是只使用内存中的模型渲染编辑操作,并放弃“理想”的 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 的答案。
关于ruby-on-rails - 如何进行渲染 :edit call show the/edit in the address bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3348920/