Ruby-on-rails 重定向中的 Flash 消息不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7426526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:58:10  来源:igfitidea点击:

Flash message in redirect not working

ruby-on-railsruby-on-rails-3

提问by chell

I have the following in my controller:

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

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

In my view I have

在我看来我有

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

But the flash message does not appear.

但是没有出现闪现信息。

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?

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

回答by Adam Eberlin

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 的保存时间不够长,无法进入最终呈现的视图。

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

一个位置优越的人flash.keep(:notice)应该可以解决问题。

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.

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

回答by chell

simple, but effective:

简单但有效:

modify ApplicationController < ActionController::Base as follows:

修改 ApplicationController < ActionController::Base 如下:

alias :std_redirect_to :redirect_to
def redirect_to(*args)
   flash.keep
   std_redirect_to *args
end

回答by Nishant Goel

IN your controller use:

在您的控制器中使用:

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

In your application layout use:

在您的应用程序布局中使用:

<%= notice %>   

回答by Muhammad Sannan Khalid

Best approach is to write these line in views/layouts/application.html.erb file

最好的方法是在 views/layouts/application.html.erb 文件中写这些行

<%= notice %>
<%= alert %>

and write

和写

layout 'application'in controllers

layout 'application'在控制器中