views:

268

answers:

2

I thought every time you do a flash[:notice]="Message" it would add it to the array which would then get displayed during the view but the following just keeps the last flash:

flash[:notice] = "Message 1"
flash[:notice] = "Message 2"

Now I realize it's just a simple hash with a key (I think :)) but is there a better way to do multiple flashes than the following:

flash[:notice] = "Message 1<br />"
flash[:notice] = "Message 2"

Thanks.

Josh

+4  A: 

The flash message can really be anything you want, so you could do something like this:

flash[:notice] = ["Message 1"]
flash[:notice] << "Message 2"

And then in your views, output it as

<%= flash[:notice].join("<br>") %>

Or whatever you prefer.

Whether that technique is easier than other solutions is determined by your own preferences.

mipadi
Good enough for me, thanks!
Josh Pinter
A: 

I usually add such methods to my ApplicationHelper:

def flash_message(type, text)
    flash[type] ||= []
    flash[type] << text
end

And

def render_flash
  rendered = []
  flash.each do |type, messages|
    messages.each do |m|
      rendered << render(:partial => 'partials/flash', :locals => {:type => type, :message => m}) unless m.blank?
    end
  end
  rendered.join('<br/>')
end

And after it is very easy to use them:

You can write something like:

flash_message :notice, 'text1'
flash_message :notice, 'text2'
flash_message :error, 'text3'

in your controller.

And just add this line to your layout:

<%= render_flash %>
Victor Savkin
Thanks Victor, that's a more thorough answer. I suppose one can make it as robust as needed. I'm still a little surprised this isn't built into the core - seems like an obvious requirement (as I type this I have three 'flash'-like notifications coming from Stack Overflow (i.e. new badge, associate my account, etc.) ;)
Josh Pinter