如何进行渲染:编辑调用在地址栏中显示/编辑

在我的Rails应用程序中的首选项控制器的更新操作中,如果validation/保存等中有任何错误,则调用:

format.html { render :edit }

没有什么太不寻常 – 但是,当这个代码被命中时,浏览器中的地址会改变并丢失URL中的/ edit。

例如:

首先,我的浏览器显示我在页面上的以下地址: http:// localhost:3000 / preferences / 1 / edit

但是,一旦检测到错误并且调用了渲染,则其中的地址将更改为http:// localhost:3000 / preferences / 1

我不能说我以前曾经注意过这种行为 – 但有没有办法强制/ edit留在URL的末尾? 没有/ edit它会有效地显示节目页面的URL(我没有这个模板!)

非常感谢,Ash

您可以redirect_to到编辑页面,并使用flash来跟踪模型,而不是调用render

 def update # ... if !@model.save # there was an error! flash[:model] = @model redirect_to :action => :edit end end 

然后在edit操作中,您可以从flash[:model]重新加载值,即:

 def edit if flash[:model] @model = flash[:model] else @model = ... # load model normally end end 

更新:

如下所述,我认为当我写这个答案时,我试图提供一种方法来更新URL(需要重定向)并保留模型的更改属性,这就是模型存储在flash中的原因。 但是,将模型粘贴到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并且您不关心维护validation失败的已更改属性,请参阅@jamesmarkcook的答案。

只需重定向到编辑路径并将模型传递给rails路径助手,如下所示:

 def update if @model.update_attributes(updated_params) // Success else redirect_to edit_model_path(@model), flash: { error: "Could not update model" } end end 

这将保留您的闪存,将您重定向到正确的路径并重新加载您的模型。