5
votes

I have this code :

def create
  login(params[:email], params[:password])

  if current_user
    flash[:notice] = "Welcome back #{current_user.email}"
    return redirect_to_first_page
  else
    flash[:notice] = "Email or password is wrong. Try again !"
    redirect_to root_url
  end
end

when the login is successful the flash is set and the redirect to the first page is made. This part is working. The second part is not setting the flash notice message. Then when the page is displayed no message from flash is show. What is different i've try to have

return redirect_to root_url

but nothing still not showing anything. In my controller i have a helper like flash_notice all it does is return flash[:notice]. This is because the flash is always empty in a view but accessible in controller. In the view i have just one line :

<%= flash_notice %>

I'm using rails 3.1

1
Does redirect_to root_url, :notice => "Email or password is wrong. Try again !" work ? - Zabba
Use only notice instead of flash_notice - Hock
@hock, flash_notice is a method on the controller defined by the OP - Zabba
Maybe another redirect is inadvertently taking place? Maybe try using flash[:notice] directly in the view? Try printing out the flash at various stages in relevant controllers and views. - Zabba
I can't use flash[:notice] in a view because is nil when in a partial view. I've try <%= "flash is nil" if flash == nil %> which was true. The only way it worked for me was to create a helper method in the base controller (e.g flash_notice) which returns the flash[:notice]. - Mihai

1 Answers

7
votes

Chris Drappier is correct, the flash hash is current for one request only. You can invoke a "keep" method with

flash.keep[:notice]="This message will persist"

Personally, I like to keep the flash in question in params when needed. The gory details are here:

http://guides.rubyonrails.org/action_controller_overview.html#the-flash