Read more

Why a Rails flash message is shown twice

Dominik Schöler
April 28, 2011Software engineer at makandra GmbH

You set a flash message and it shows up as it should. However, it is displayed again the next time you follow a link. Here is why:

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

You have to differentiate between a render and a redirect_to because a flash message is only deleted after a redirect. If you want a message to be seen in the next request after a redirect, use flash[]. If you want a message to be seen in the current request, use flash.now[].

Workaround for the lazy

If you cannot be bothered to decide which flash hash to use, or if the flash is set by a piece of code outside your control, you can also change your layout displaying the flash so it deletes the flash message once displayed:

- flash.slice(:notice, :message, :error, :success, :warning, :failure).each do |level, value|
  - if value.present?
    %div{:class => "flash #{h level}"}
      = h value
      - flash[level] = nil # set to nil in case the flash was set without a following redirect
Posted by Dominik Schöler to makandra dev (2011-04-28 12:20)