如何在redirect时显示Rails Flash通知?

我在Rails控制器中有以下代码:

flash.now[:notice] = 'Successfully checked in' redirect_to check_in_path 

然后在/ check_in视图中:

 <p id="notice"><%= notice %></p> 

但是,通知不显示。 如果我不在控制器中redirect,则工作完美:

 flash.now[:notice] = 'Successfully checked in' render action: 'check_in' 

我需要一个redirect,虽然…不只是一个渲染的行动。 redirect后可以收到Flash通知吗?

删除“.now”。 所以只要写:

 flash[:notice] = 'Successfully checked in' redirect_to check_in_path 

当你只是渲染而不是redirect的时候,.now是专门用来做的。 redirect时,现在不能使用。

 redirect_to new_user_session_path, alert: "Invalid email or password" 

代替:alert您可以使用:notice

显示

或者你可以在一行。

 redirect_to check_in_path, flash: {notice: "Successfully checked in"} 

我有同样的问题,你的问题解决了我的,因为我忘记了包含在/ check_in视图:

 <p id="notice"><%= notice %></p> 

在控制器中,只有一行:

 redirect_to check_in_path, :notice => "Successfully checked in" 

这也会起作用

redirect_to check_in_path, notice: 'Successfully checked in'

如果您正在使用Bootstrap,则会在您redirect的目标页面上显示格式良好的Flash消息。

在你的控制器中:

 if my_success_condition flash[:success] = 'It worked!' else flash[:warning] = 'Something went wrong.' end redirect_to myroute_path 

在你看来:

 <% flash.each do |key, value| %> <div class="alert alert-<%= key %>"><%= value %></div> <% end %> 

这将产生如下的HTML:

 <div class="alert alert-success">It worked!</div> 

有关可用的引导警报样式,请参阅: http : //getbootstrap.com/docs/4.0/components/alerts/

参考: https : //agilewarrior.wordpress.com/2014/04/26/how-to-add-a-flash-message-to-your-rails-page/

Interesting Posts