Rails: Easy way to add more than one flash[:notice] at a time

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 %>

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.


I think the idea built into the framework is that every message you stick into flash is over-writeable. You give each message a unique key so you can change or overwrite it.

If you need another message, don't call it ":notice." Call each something unique. Then to render the flash messages, loop through whatever is in the hash.

If this doesn't work for you, consider whether you actually need to simplify your UI.


Although I agree with Jonathan in that the UI might need some simplification, there are instances where you might want to display multiple messages for the same key.

As a result, I have created a gem that (should) make it easy to deal with multiple flash messages in the same key and their rendering in the view.

GitHub: flash-dance