chell
chell

Reputation: 7866

Flash message in redirect not working

I have the following in my controller:

redirect_to signin_path, :notice => "The email is already registered"

In my view I have

<%= flash[:notice] if flash[:notice] %>

But the flash message does not appear.

However if I do the following in the controller

flash[:notice] = "There is already an acount for this email. Please Login to create your board."
redirect_to signin_path

It does work. What is the reason the first one does not work?

Upvotes: 30

Views: 23130

Answers (4)

Adam Eberlin
Adam Eberlin

Reputation: 14205

Do some tail'ing on your logs and see if you're being redirected to multiple actions before you render. If you are, it's likely that flash isn't being kept long enough to make it to the view where it is finally rendered.

A well-placed flash.keep(:notice) should do the trick.

Much later edit: Also, in retrospect, if you're redirecting that many times, I highly suggest you do some refactoring and eliminate any unnecessary jumps by consolidating your redirect logic at a higher level, so that your redirects are predetermined and only happen once, twice max.

Upvotes: 37

Nishant Goel
Nishant Goel

Reputation: 77

IN your controller use:

redirect_to signin_path, :notice => "There is already an acount for this email. Please Login to create your board."

In your application layout use:

<%= notice %>   

Upvotes: 1

user1212110
user1212110

Reputation:

simple, but effective:

modify ApplicationController < ActionController::Base as follows:

alias :std_redirect_to :redirect_to
def redirect_to(*args)
   flash.keep
   std_redirect_to *args
end

Upvotes: 6

Muhammad Sannan Khalid
Muhammad Sannan Khalid

Reputation: 3137

Best approach is to write these line in views/layouts/application.html.erb file

<%= notice %>
<%= alert %>

and write

layout 'application' in controllers

Upvotes: 1

Related Questions