代码之家  ›  专栏  ›  技术社区  ›  Ash

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

  •  2
  • Ash  · 技术社区  · 16 年前

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

    format.html { render :edit }

    这里没有什么特别之处——但是,当点击此代码时,浏览器中的地址会更改并丢失URL中的/edit。

    例如:

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

    但是,一旦检测到错误并调用呈现,中的地址将更改为 http://localhost:3000/preferences/1

    我不能说我以前注意到过这种行为——但是有没有一种方法可以强制/编辑停留在URL的末尾?如果没有/edit,它将有效地显示显示显示页的URL(我没有用于此的模板!)

    多谢, 灰分

    2 回复  |  直到 9 年前
        1
  •  5
  •   Daniel Vandersluis    9 年前

    而不是打电话 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包含 编辑 .

    通常的模式是只渲染模型已经在内存中的编辑操作,而放弃使用“理想”的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的答案。

        2
  •  0
  •   James    9 年前

    只需重定向到编辑路径并将模型传递给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
    

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