How to display a Rails flash notice upon redirect?

Ruby on-RailsRuby on-Rails-3Ruby on-Rails-3.2Ruby on-Rails-4Rails Flash

Ruby on-Rails Problem Overview


I have the following code in a Rails controller:

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

Then in the /check_in view:

<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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Remove the .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. When redirecting, the .now is not to be used.

Solution 2 - Ruby on-Rails

redirect_to new_user_session_path, alert: "Invalid email or password"

in place of :alert you can use :notice

to display

Solution 3 - Ruby on-Rails

Or you can do it in one line.

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

Solution 4 - Ruby on-Rails

This will work too

Solution 5 - Ruby on-Rails

If you are using Bootstrap, this will display a nicely-formatted flash message on the page that's the target of your redirect.

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:

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

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/

Solution 6 - Ruby on-Rails

I had the same problem, and your question solved mine, because I had forgotten to include in the /check_in view:

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

In the controller, just a single line:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionat.View Question on Stackoverflow
Solution 1 - Ruby on-RailsRebitzeleView Answer on Stackoverflow
Solution 2 - Ruby on-RailsTauqeer AhmadView Answer on Stackoverflow
Solution 3 - Ruby on-RailsetldsView Answer on Stackoverflow
Solution 4 - Ruby on-RailsSeiferView Answer on Stackoverflow
Solution 5 - Ruby on-RailsJon SchneiderView Answer on Stackoverflow
Solution 6 - Ruby on-RailsFlorencio LugoView Answer on Stackoverflow