I can't figure out why my flash messages disappear after a redirect_to. Started the debugger in my view, and the flash variable is totally empty.
flash
=> {}
The result is the same with flash.now... It works fine if I edit something and call render.
Controller:
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash[:notice] = "Logged in"
redirect_to root_url
else
render :action => 'new'
end
end
Application layout:
- flash.each do |name, msg|
=content_tag :div, msg, :class => "flash_#{name}"
root_url is another controller and action.
When you use the flash messages feature, there are two ways of displaying messages:
Instantly on the same page load, and accessible in the view from flash['foo']
:
flash.now['foo'] = "Hello world"
Or on a redirect to another page, and accessible from flash['notice']
:
redirect_to root_url, notice: "Hello world"
The ruby on rails guides website is a really good reference:
http://guides.rubyonrails.org/action_controller_overview.html#the-flash
If you are using a double redirect (e.g. redirect to root, which then redirects to user), you need to pass the flash on.
def first_action
flash[:notice] = "Logged in"
redirect_to root_url
end
def second_redirect_action
redirect_to current_user, flash: flash
end
I just ran into this issue too, in Rails 4, and after banging my head against my computer for a while, I noticed this in the Rails logs: Can't verify CSRF token authenticity
.
Turned out, I was submitting via a form that didn't have a CSRF token in it. Surprisingly, it was still calling my controller method and still doing the redirect, but this was what was throwing everything off.
Adding a CSRF token to my form fixed it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With