如何在重定向时显示Rails的闪存通知?

73

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

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

然后在/check_in视图中:

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

然而,通知未显示。如果我在控制器中不进行重定向,则完美运行:

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

我需要进行重定向...而不仅仅是渲染该操作。 重定向后能否显示flash提示?

6个回答

130

移除 .now。只需写成:

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

.now 特别适用于仅呈现内容而不进行重定向的情况。在重定向时,不应使用 .now


太好了!谢谢。由于某种原因,它让我等待6分钟才能接受答案... - at.

45
redirect_to new_user_session_path, alert: "Invalid email or password"

您可以使用:notice代替:alert

来显示


22

或者您可以在一行中完成它。

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

@JayEl-Kaake,你使用的是哪个Ruby版本? - etlds
那是一段时间之前的事情了,所以我不确定...看起来应该可以,我会撤回我的评论。 - Jay El-Kaake
2
路径,flash: {notice: ... 看起来像是Rails 3,而路径,alert: ... 是Rails 4+。 - Simon B.
1
不错的解决方案,因为它还允许不同类型的消息,例如闪现:{success:“文本”}。 - fydelio

13

这也可以正常工作

redirect_to check_in_path, notice: '成功签到'


11
如果您正在使用Bootstrap,这将在页面上显示一个漂亮格式的闪存消息,该消息是您重定向的目标。
在您的控制器中:
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>

查看可用的Bootstrap警告样式,请参见: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/


3

我遇到了同样的问题,而你的问题解决了我的问题,因为我忘记在/check_in视图中包含以下内容:

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

在控制器中,只需要一行代码:
redirect_to check_in_path, :notice => "Successfully checked in"             

你的问题不同。我有<%= notice %>标签,只是没有任何内容显示出来。 - at.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接