重定向中的 Flash 消息不起作用

问题描述:

我的控制器中有以下内容:

I have the following in my controller:

redirect_to signin_path, :notice => "The email is already registered"

在我看来我有

<%= flash[:notice] if flash[:notice] %>

但是闪消息没有出现.

但是,如果我在控制器中执行以下操作

However if I do the following in the controller

flash[:notice] = "There is already an acount for this email. Please Login to create your board."
redirect_to signin_path

确实有效.第一个不起作用的原因是什么?

It does work. What is the reason the first one does not work?

在您的日志上做一些跟踪,看看您是否在渲染之前被重定向到多个操作.如果是,则可能是 Flash 保存的时间不够长,无法进入最终呈现的视图.

Do some tail'ing on your logs and see if you're being redirected to multiple actions before you render. If you are, it's likely that flash isn't being kept long enough to make it to the view where it is finally rendered.

位置良好的 flash.keep(:notice) 应该可以解决问题.

A well-placed flash.keep(:notice) should do the trick.

后期此外,回想起来,如果您重定向了很多次,我强烈建议您进行一些重构并通过在更高级别合并重定向逻辑来消除任何不必要的跳转,以便您的重定向是预先确定的,并且只发生一次,最多两次.

Much later edit: Also, in retrospect, if you're redirecting that many times, I highly suggest you do some refactoring and eliminate any unnecessary jumps by consolidating your redirect logic at a higher level, so that your redirects are predetermined and only happen once, twice max.