nei*_*led 5 controller ruby-on-rails render ruby-on-rails-3
好的,所以我有一个用户 has_one 模板,我想要的页面基本上只是模板的编辑视图。
我有:
class TemplatesController < ApplicationController
def edit
@template = current_user.template
end
def update
@template = current_user.template
if @template.update_attributes(params[:template])
flash[:notice] = "Template was successfully updated"
end
render :edit
end
Run Code Online (Sandbox Code Playgroud)
结束
现在,“问题”是当我调用render:edit时,实际上我最终在/template.1而不是/ template / edit上,这正是我所期望的。显然,如果我调用redirect_to:edit,那么我会得到预期的路径,但是如果有的话,我会放宽对象错误。
有一个更好的方法吗?
谢谢!!
通常,在编辑/更新操作对中,如果出现错误,您只会重新渲染更新中的编辑,并相应地设置闪存。如果您已经在 template/1/edit 上(这是我所期望的),那么 url 逻辑上不会改变,因为您告诉浏览器简单地呈现您发送的文本。这是预期的行为。如果您成功更新,那么您可以重定向到显示或索引或任何您需要从那里去的地方,并且闪光灯将保留通知文本(这就是闪光灯的用途),即使模型不会。请注意,对于渲染操作,您需要使用 Flash.now,以便该消息不会在下一次重定向时保留。
def update
@template = current_user.template
if @template.update_attributes(params[:template])
flash[:notice] = "Template was successfully updated"
redirect_to(@template)
else
flash.now[:error] = @template.errors[:base]
render :edit
end
end
Run Code Online (Sandbox Code Playgroud)