如何在rails3中呈现编辑视图和发布flash消息

Oli*_*ier 32 view ruby-on-rails-3

在我的帐户控制器中,我想在保存更改并显示闪存通知后显示(渲染,重定向?)编辑视图.

 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
Run Code Online (Sandbox Code Playgroud)

Bri*_*ing 43

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

format.html { 
  flash[:notice] = 'message'
  render :edit
}
Run Code Online (Sandbox Code Playgroud)

此票证有一个允许您使用的补丁render 'edit', :notice => 'message'.它没有进入Rails,但有一个gem,flash_render,它添加了它.

  • 如果你使用`render`(而不是`redirect_to`),你通常想要使用`flash.now`.我在[此博客文章]中详细解释了原因(http://ryanlue.com/posts/2017-08-24-rails-render#implications-for-flash). (3认同)

Max*_*akh 11

您仍然可以使用Rails 2中的通知:

flash[:notice] = "message"
Run Code Online (Sandbox Code Playgroud)

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

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

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


ste*_*ser 11

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

format.html { 
  flash.now[:notice] = 'message'
  render :edit
}
Run Code Online (Sandbox Code Playgroud)

供参考阅读操作控制器概述5.2.1