【问题标题】:Why does the render method change the path for a singular resource after an edit?为什么 render 方法在编辑后会更改单个资源的路径?
【发布时间】:2010-12-17 22:40:02
【问题描述】:

好的,所以我有一个 User,它有一个 Template,我想要一个基本上只是 Template 的编辑视图的页面。

我有:

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

结束

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

有没有更好的方法来做到这一点?

谢谢!!

【问题讨论】:

    标签: ruby-on-rails controller render ruby-on-rails-3


    【解决方案1】:

    通常在编辑/更新操作对中,如果出现错误,您只会从更新中重新渲染编辑,并相应地设置闪存。如果您已经在 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
    

    【讨论】:

      【解决方案2】:

      如果您使用的是单一资源,您希望在路由中使用 resolve。见this in the Rails Guides

      resource :geocoder
      resolve('Geocoder') { [:geocoder] }
      

      【讨论】:

        【解决方案3】:

        在我看来,你不能松开模板对象(在编辑操作中),因为你是从用户模型中获得的

        render edit_template_patch(@template)
        

        你会得到template/:id/edit 例如。 template/1/edit

        【讨论】:

        • render 采用动作/方法,不是路径,也不是补丁。即使你调用了正确的方法redirect_to,你也会丢失模型上的错误,这是OP所关心的。
        猜你喜欢
        • 1970-01-01
        • 2015-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-25
        • 1970-01-01
        • 2021-12-15
        相关资源
        最近更新 更多