Flash messages stay up too long

I run a check on the address line parameters to make sure the user isn’t
passing my list method a :year to search for that does not exist in the
database, which would create null pointer exceptions. I then splash a
flash message telling the user that the year doesn’t exist in the
database. Then, if the user enters another year into the command line
as an argument for the action, list, a year that does exist in the
database, the flash message is still displayed on this next render of
list. It is not until the second correct page is shown that the flash
message goes away. How do I fix this?

Sam

Should you perhaps be using flash.now[:notice] instead of flash[:notice]
?

Fred

Thanks. I’m curious abot the difference. I’ll look it up.

Sam

Frederick C. wrote:

Should you perhaps be using flash.now[:notice] instead of flash[:notice]
?

Fred

As I understand it, Flash persists to the next request, and Flash.now is
only the current request. Some examples…

Flash[:notice] = “blah”
The view for this action will show the message, as well as the next
request you make (assuming the action for the next request does not have
a redirect_to in it).

Flash.now[:notice] = “blah”
Only the view for this action will show the message, the next request
won’t have it.

Flash[:notice] = “blah”
redirect_to :action => “nextaction”
The view for the “nextaction” action will show the message, and it will
disappear on the following request.

Flash.now[:notice] = “blah”
redirect_to :action => “next”
The message will not be shown.

At least - I think that’s how it works. For instance, I have this index
action in my store controller:

def index
@cart = find_cart
flash[:notice] = “Your cart is empty” unless @cart.items.size > 0
end

If I go to site/store/index, I will see my cart and the “empty” message.
If I then click “Account History”, I’ll go to that page and the message
will still be there, after that it will go away on the next request.
This is because Flash persists through the current request (for
store/index) and into the next request (for store/account). If I change
it to Flash.now, then it only lasts for the current request and does not
persist through.

c.

Sam W. wrote:

Thanks. I’m curious abot the difference. I’ll look it up.

Sam

Frederick C. wrote:

Should you perhaps be using flash.now[:notice] instead of flash[:notice]
?

Fred

On 10/25/06, Sam W. [email protected] wrote:

Do you, by any chance, set the flash and then redirect from a before
filter?

That initial request isn’t counted, a bug imo – think that was the
consensus when this was brought up on rails-core as well, so the flash
thinks it’s jsut been set when serving the next request, and that it’s
supposed to stay for 1 more page.

Been a few months since I looked into this, the above may not be
correct any more.

The workaround would be to use flash.now, yes.

Isak