为什么render方法在编辑后更改单个资源的路径? [英] Why does the render method change the path for a singular resource after an edit?

查看:62
本文介绍了为什么render方法在编辑后更改单个资源的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个用户,它具有一个 Template ,并且我想要一个页面,该页面基本上只是 Template 的编辑视图。 / p>

我有:

  class TemplatesController< ApplicationController 
def编辑
@template = current_user.template
结束

def更新
@template = current_user.template
(如果@template)。 update_attributes(params [:template])
flash [:notice] =模板已成功更新
结束
渲染:edit
结束

end



现在问题是当我调用render时:edit我实际上最终在/template.1而不是/ template / edit上,这是我期望的。显然,如果我调用redirect_to:edit,那么我会得到我期望的路径,但是如果有的话,我会放宽对象错误。



有没有更好的方法



谢谢!

解决方案

通常在编辑中/ update操作对,则只有在出现错误时才从渲染中重新渲染编辑,并相应地设置Flash。如果您已经在使用template1 / 1 / edit(这是我所期望的),那么该URL在逻辑上不会改变,因为您是在告诉浏览器仅呈现要发送的文本。这是预期的行为。如果更新成功,则可以重定向到显示或索引或需要从那里进行的任何操作,并且即使模型没有显示,Flash也会保留通知文本(这是Flash的目的)。请注意,对于渲染操作,您需要使用Flash.now,以便消息不会在下一次重定向时持续存在。

  def更新
@template = current_user.template
如果@ template.update_attributes(params [:template ])
flash [:notice] =模板已成功更新
redirect_to(@template)
else
flash.now [:error] = @ template.errors [:基本]
渲染:edit
结束
结束


OK so I have a User which has_one Template and I want a page which is basically just an edit view of the Template.

I have:

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

end

Now the 'problem' is when I call render :edit I actually end up on /template.1 instead of /template/edit which is what I'd expect. Obviously if I call redirect_to :edit then I'd get the path I expect but I'd loose the object errors if there were any.

Is there a better way to do this?

Thanks!!

解决方案

Normally in an edit/update action pair you would only re-render the edit from update if there were errors, setting the flash accordingly. If you were already on template/1/edit (which is what I would expect), then the url logically won't change since you're telling the browser to simply render the text you're sending it. This is expected behavior. If you were successful in updating then you can redirect to show or index or wherever you need to go from there, and the flash will keep the notice text (that's what the flash is for) even though the model won't. Note that for a render action you need to use Flash.now so that the message won't persist on the next redirect.

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

这篇关于为什么render方法在编辑后更改单个资源的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆