Reputation: 3068
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.
Upvotes: 20
Views: 17780
Reputation: 4551
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.
Upvotes: 6
Reputation: 2144
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
Upvotes: 7
Reputation: 360
My flash rendering wasn't working for root_url because of my routing. I had the root_url redirected to one another page, like root :to => redirect('[SOME_OTHER_PAGE]'). Instead of this I just use redirect_to to another resource
Upvotes: 1
Reputation: 1326
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
Upvotes: 24
Reputation: 825
if you are redirect to another action use flash and if you are render to same action use flash.now
Upvotes: 0