简体   繁体   English

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

[英]How to display a Rails flash notice upon redirect?

I have the following code in a Rails controller:我在 Rails 控制器中有以下代码:

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

Then in the /check_in view:然后在 /check_in 视图中:

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

However, the notice does not show up.但是,该通知并未显示。 Works perfect if I don't redirect in the controller:如果我不在控制器中重定向,则工作完美:

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

I need a redirect though... not just a rendering of that action.不过,我需要重定向……而不仅仅是该操作的渲染。 Can I have a flash notice after redirecting?重定向后我可以收到闪现通知吗?

Remove the .now .删除.now So just write:所以只需写:

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

The .now is specifically supposed to be used when you are just rendering and not redirecting.当您只是渲染而不是重定向时,特别应该使用.now When redirecting, the .now is not to be used.重定向时,不使用.now

redirect_to new_user_session_path, alert: "Invalid email or password"

in place of :alert you can use :notice您可以使用:notice代替:alert

to display显示

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

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

If you are using Bootstrap, this will display a nicely-formatted flash message on the page that's the target of your redirect.如果您使用的是 Bootstrap,这将在您重定向的目标页面上显示格式良好的 Flash 消息。

In your controller:在您的控制器中:

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

In your view:在您看来:

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

This will produce HTML like:这将产生如下 HTML:

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

For available Bootstrap alert styles, see: http://getbootstrap.com/docs/4.0/components/alerts/有关可用的 Bootstrap 警报样式,请参阅: 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/参考: https : //agilewarrior.wordpress.com/2014/04/26/how-to-add-a-flash-message-to-your-rails-page/

这也行

redirect_to check_in_path, notice: 'Successfully checked in'

I had the same problem, and your question solved mine, because I had forgotten to include in the /check_in view:我遇到了同样的问题,你的问题解决了我的问题,因为我忘记包含在 /check_in 视图中:

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

In the controller, just a single line:在控制器中,只有一行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM