Knowing when to use flash.now

The flash hash is designed to carry a message from one action to the next. Here’s a simple example:

def create
  @user = User.create params[:user]
  if @user.save
    flash[:notice] = "User account created - Sweet!"
    redirect_to @user  
  else
    render :action => "new"
  end
end

You’ve probably seen examples like this a hundred times. A new user is created, the flash[:notice] is set to “User account created – Sweet!” and then the user is re-directed to the show action where the notice is displayed. However, if the @user object is not valid, there’s no redirect. Instead, the new template is rendered but we’re still in the create action.

Suppose you wanted to display a message on screen if there’s an error with the user record; a message that will be displayed when the new page is re-rendered. We could use the flash hash here too:

def create
  @user = User.create params[:user]
  if @user.save
    flash[:notice] = "User account created - Sweet!"
    redirect_to @user
  else
    flash[:error] = "Couldn't create user - Damn!"
    render :action => "new"
  end
end

However, because the flash hash is designed to be available to the next action, if the user then moves on to another page they’ll still see the error message displayed on the screen. Not only does this look pretty bad, it could confuse your users if they see an error message when there is no longer an error.

To display a flash message on the current action, a message that will not be carried on to the next action, use flash.now:

def create
  @user = User.create params[:user]
  if @user.save
    flash[:notice] = "User account created - Sweet!"
    redirect_to @user
  else
    flash.now[:error] = "Couldn't create user - Damn!"
    render :action => "new"
  end
end

In this case, the error message will be displayed on screen when the new page is re-rendered but will not be carried on to the next.

Written by

Photo of Gavin Morrice
Gavin Morrice

Software engineer based in Scotland

Work with me

Need help with some code?

In my free time, I like to help people improve their code and skills on Codementor.
Contact me on Codementor