【问题标题】:How to render edit view and post flash message in rails3如何在 rails3 中呈现编辑视图并发布 flash 消息
【发布时间】:2011-06-13 20:01:34
【问题描述】:

在我的帐户控制器中,我想在保存更改后显示(渲染、redirect_to ?)编辑视图并显示 Flash 通知。

 def update
    @account = Account.find(params[:id])

    respond_to do |format|
      if @account.update_attributes(params[:account])
        format.html { redirect_to(@account, :notice => 'Account was successfully updated.') }

      else
        format.html { render :action => "edit" }
      end
    end
  end

【问题讨论】:

    标签: ruby-on-rails-3 view


    【解决方案1】:

    如果您只使用flash[:notice],该值在下一个请求中仍然可用。意思是,您将在接下来的 2 页中看到文本。而是使用flash.now 仅使该值在当前请求中可用。

    format.html { 
      flash.now[:notice] = 'message'
      render :edit
    }
    

    参考阅读Action Controller Overview 5.2.1

    【讨论】:

      【解决方案2】:

      你仍然可以像在 Rails 2 中一样使用通知:

      flash[:notice] = "message"
      

      只需将以下行添加到视图顶部即可显示它:

      <p id="notice"><%= flash[:notice] %></p>

      如果您不想让您的用户再次填写编辑表单,您应该使用render 方法。

      【讨论】:

      • 我不明白你最后的评论。更新后redirect_to 是标准的,因此浏览器刷新不会再次提交。 “再次填写编辑表单”部分让我感到困惑。
      • 实际上这是我的错误,在您的情况下,这些方法之间确实没有区别。所以使用任何你想要的。
      • @timkay 但不要忘记renderredirect_to 是完全不同的方法。阅读Rails Guides on Rendering了解更多信息。
      • @timkay 更新失败时重定向会清除表单中任何以前编辑过的数据,这对最终用户来说会很烦人。
      【解决方案3】:

      默认情况下,您必须使用单独的语句,例如

      format.html { 
        flash[:notice] = 'message'
        render :edit
      }
      

      This ticket 有一个补丁可以让你使用render 'edit', :notice => 'message'。它没有进入 Rails,但有一个 gem,flash_render,添加了它。

      【讨论】:

      • 如果您使用render(而不是redirect_to),您通常希望使用flash.now。我在this blog post中详细解释了原因。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      相关资源
      最近更新 更多