Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, losing flash after redirect_to

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.

like image 824
atmorell Avatar asked Jul 22 '09 14:07

atmorell


Video Answer


3 Answers

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

like image 109
Nico Avatar answered Sep 27 '22 22:09

Nico


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
like image 32
James EJ Avatar answered Sep 27 '22 21:09

James EJ


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.

like image 23
Christopher Davies Avatar answered Sep 27 '22 22:09

Christopher Davies