Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails flash :notice doesn't work

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

like image 318
Mihai Avatar asked Oct 07 '11 19:10

Mihai


People also ask

How does Flash work in Rails?

A flash message is a way to communicate information with the users of your Rails application so they can know what happens as a result of their actions. Example messages: “Password changed correctly” (confirmation) “User not found” (error)

How do I use flash in Ruby on Rails?

In order to implement flash in your own apps, there's a specific set of steps that must be taken. You first call and set flash in your action controller. You must tell flash precisely what you want it to persist forward. Redirect your action controller to the full-page reload of your choice.

What is a flash notice?

Flash messages are notifications and alerts that pop up in the interface of an application in order to communicate with the user and ease of interaction. Applications often apply flash messages to tell the user if the login was correct or to confirm the success of the action triggered by clicking a button.

How do I redirect back in Rails?

In Rails 4. x, for going back to previous page we use redirect_to :back. However sometimes we get ActionController::RedirectBackError exception when HTTP_REFERER is not present. This works well when HTTP_REFERER is present and it redirects to previous page.


1 Answers

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

like image 186
Perry Horwich Avatar answered Sep 20 '22 02:09

Perry Horwich