Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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" 
like image 799
Joshua Pinter Avatar asked Mar 15 '10 16:03

Joshua Pinter


2 Answers

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 %> 
like image 163
Victor Savkin Avatar answered Sep 20 '22 13:09

Victor Savkin


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.

like image 33
mipadi Avatar answered Sep 21 '22 13:09

mipadi