Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails flash[:notice] always nil

I cannot figure out why my rails views are not recognizing flash[:notice] or flash[:error]. I keep getting the following error regarding the partial view being rendered. The specific error is:

ActionView::Template::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.[]):

In my controller I have

  def index
    @organisms = Organism.all
    flash[:error] = "test"
    flash[:notice] = "test"
    respond_to do |format|
      format.html
      format.json  { render :json => @organisms }
    end
  end

In my index.html.erb file I render out a partial through:

<%= render "shared/flash" %>

The partial has the following code.

<div id="flashes">

  <% if flash[:notice] %>
    <p id="flash_notice" class="messages notice"><%= flash[:notice] %></p>
    <%= javascript_tag "$('#flash_notice').effect('highlight',{},1000);" %>
  <% end %>
  <% if flash[:error] || flash[:errors] %>
    <p id="flash_errors" class="messages errors"><%= flash[:error] || flash[:errors] %></p>
    <%= javascript_tag "$('#flash_errors').effect('highlight',{},1000);" %>
  <% end %>

  <% flash[:error] = flash[:errors] = flash[:notice] = nil %>
</div>

However, if instead of rendering the partial I throw in <%= notice %> it renders out the notice.

If I take the partial code and stick it in the top of the index.html.erb file it renders correctly. Thus, I assume that I am rendering the partial view wrongly?

Any help is much appreciated. Thanks!

like image 807
Phillip Whisenhunt Avatar asked Nov 01 '11 19:11

Phillip Whisenhunt


2 Answers

Don't name your partial flash. Ruby on Rails creates a local variable with the same name as the partial. In your case, a flash local variable is being created.

Rename your partial to something other than flash and it should work.

Also, you shouldn't need to set flash to nil at the bottom of your partial. Let Rails take care of that for you.

like image 86
Robert Grimm Avatar answered Sep 19 '22 21:09

Robert Grimm


You have to pass the flash to the partial:

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

Or a bit longer:

<%= render partial: 'shared/flash', locals: { flash: flash } %>
like image 2
Damien Avatar answered Sep 21 '22 21:09

Damien