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

at.*_*at. 58 ruby-on-rails rails-flash ruby-on-rails-3 ruby-on-rails-3.2 ruby-on-rails-4

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

flash.now[:notice] = 'Successfully checked in'
redirect_to check_in_path
Run Code Online (Sandbox Code Playgroud)

然后在/ check_in视图中:

<p id="notice"><%= notice %></p>
Run Code Online (Sandbox Code Playgroud)

但是,通知没有显示出来.如果我不在控制器中重定向,则工作完美:

flash.now[:notice] = 'Successfully checked in'
render action: 'check_in'
Run Code Online (Sandbox Code Playgroud)

我需要重定向...而不仅仅是对该动作的渲染.重定向后可以有闪光通知吗?

Reb*_*ele 109

删除".now".所以写一下:

flash[:notice] = 'Successfully checked in'
redirect_to check_in_path
Run Code Online (Sandbox Code Playgroud)

.now特别应该在您只是渲染而不是重定向时使用.重定向时,不使用.now.


Tau*_*mad 35

redirect_to new_user_session_path, alert: "Invalid email or password"
Run Code Online (Sandbox Code Playgroud)

代替:alert你可以使用:notice

显示


etl*_*lds 16

或者你可以在一行中完成.

redirect_to check_in_path, flash: {notice: "Successfully checked in"}
Run Code Online (Sandbox Code Playgroud)

  • 路径,flash:{注意:......好像是Rails 3,而路径,警告:......是Rails 4+ (2认同)

Jon*_*der 6

如果您使用的是Bootstrap,则会在重定向目标页面上显示格式正确的Flash消息。

在您的控制器中:

if my_success_condition
  flash[:success] = 'It worked!'
else
  flash[:warning] = 'Something went wrong.'
end
redirect_to myroute_path
Run Code Online (Sandbox Code Playgroud)

您认为:

<% flash.each do |key, value| %>
  <div class="alert alert-<%= key %>"><%= value %></div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

这将产生如下的HTML:

<div class="alert alert-success">It worked!</div>
Run Code Online (Sandbox Code Playgroud)

For available Bootstrap alert styles, see: http://getbootstrap.com/docs/4.0/components/alerts/

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


Sei*_*fer 5

这也将工作

redirect_to check_in_path, notice: 'Successfully checked in'