在我的Rails应用程序中的首选项控制器的更新操作中,如果验证/保存等中有任何错误,则会调用:
format.html { render :edit }
没有什么太不寻常 - 但是,当这个代码被点击时,浏览器中的地址会改变并丢失URL中的/ edit。
例如:
首先,我的浏览器显示我在以下地址的页面上:http://localhost:3000/preferences/1/edit
但是,一旦检测到错误并且调用了渲染,则其中的地址将更改为http://localhost:3000/preferences/1
我不能说我以前曾经注意过这种行为 - 但有没有办法强制/ edit留在URL的末尾?没有/ edit它会有效地显示节目页面的URL(我没有这个模板!)
非常感谢, 灰
答案 0 :(得分:5)
您可以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]
重新加载值,即:
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并且您不关心维护验证失败的更改属性,请参阅@jamesmarkcook的答案。
答案 1 :(得分:0)
只需重定向到编辑路径,然后将模型传递给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
这将保留您的闪光灯,将您重定向到正确的路径并重新加载您的模型。