Rails Flash消息仍然是两页加载

Pau*_*ell 65 ruby ruby-on-rails

我在Rails应用程序中使用闪存通知,使用以下代码:

flash[:notice] = "Sorry, we weren't able to log you in with those details."
render :action => :new
Run Code Online (Sandbox Code Playgroud)

Flash消息在"新"操作上按预期呈现,但随后它也会显示用户访问的下一页(无论可能是什么).它应该只显示一次,但有些东西会让它坚持下去.

Sim*_*tti 128

有两种方法可以解决这个问题:

一个是使用

flash.now[:notice]
Run Code Online (Sandbox Code Playgroud)

当您的闪存必须在当前请求结束时丢弃,并且不打算在重定向后使用.

第二个是打电话

flash.discard(:notice)
Run Code Online (Sandbox Code Playgroud)

在请求结束时.

标准闪存消息旨在保留"下一个"请求.例如,您在处理创建或编辑请求时生成闪存,然后将用户重定向到显示屏幕.当浏览器向显示屏幕发出下一个请求时,将显示闪存.

如果您在显示屏幕上实际生成闪光灯,请使用flash.now.

查看Ruby on Rails API文档,了解Flash哈希的工作原理


Pau*_*ell 15

好的,我解决了这个问题.解决它的方法是使用:

flash.now[:notice] = "Sorry, we weren't able to log you in with those details."
render :action => :new
Run Code Online (Sandbox Code Playgroud)

关键部分是flash.now [:notice]而不是flash [:notice].