Topic: Needs help with creating a flash message partial!

Hello!

I'm trying to create a partial for flash messages and render it in my
views, but I don't get it to work. My code looks like this:

# _flash.html.erb 
<% flash.each do |key, value| %> 
        <%= content_tag(:div, value, :class => "flash #{key} body_copy 
box_padding") %> 
<% end %>

And in my views:

<%= render 'shared/flash' %>

And I get the the following error:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

Any help would be really appreciated!

Thanks!

// Anders

Last edited by Anders_P (2010-09-08 15:26:40)

Re: Needs help with creating a flash message partial!

I've soloved it by by passing the flash object, like so:

<%= render :partial => 'shared/flash', :object => flash %>

With help from radhames brito.

Re: Needs help with creating a flash message partial!

You should do this instead:

<%= content_tag(:div, flash.delete(key), ...) %>

If you don't delete the key, your message will be persistent between pages until you change it in another action.

Regards

Re: Needs help with creating a flash message partial!

I've always kept my flash messages in a helper method which I call in my layout file. Always found it much cleaner, especially if you're using content_tag.

# application_helper.rb

def flash_messages
    flash.each do |key, value|
       content_tag(:div, value, :class => "flash #{key} body_copy box_padding")
    end
end

# application.html.erb

<%= flash_messages %>