How to display a Rails notification when redirecting?

I have the following code in a Rails controller:

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

Then in the view / check _in:

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

However, a notification does not appear. Works great if I don't redirect to the controller:

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

I need a redirect though ... not just rendering this action. Can I get a flash notification after a redirect?

+42
ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 rails-flash
Mar 20 '13 at 20:33
source share
6 answers

Remove the ".now". So just write:

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

It is currently assumed that it is only used when you are just rendering and not redirecting. When redirecting, you cannot use .now.

+87
Mar 20 '13 at 20:39
source share
 redirect_to new_user_session_path, alert: "Invalid email or password" 

instead of :alert you can use :notice

to display

+19
Mar 21 '13 at 10:52
source share

Or you can do it on one line.

 redirect_to check_in_path, flash: {notice: "Successfully checked in"} 
+9
Dec 12 '14 at 16:10
source share

I had the same problem and your question was solved by mine because I forgot to include / check _in in the view:

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

There is only one line in the controller:

 redirect_to check_in_path, :notice => "Successfully checked in" 
+3
Feb 08 '15 at 18:44
source share

This will work too

redirect_to check_in_path, notice: 'Successfully checked in'

+2
May 25 '16 at 13:49
source share

If you use Bootstrap, this will display on the page a well-formatted flash message that your redirect is aimed at.

In your controller:

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

In your opinion:

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

This will create the HTML as:

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

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

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

0
05 Oct '17 at 20:41
source share



All Articles