17
votes

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.

6
and can you post the code for the root_url controller/action you're redirecting to?Mark S.

6 Answers

24
votes

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

7
votes

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
5
votes

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.

4
votes

It was the render_component plugin. It breaks rails 2.3.2.

1
votes

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

0
votes

if you are redirect to another action use flash and if you are render to same action use flash.now