Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Railstutorial: Putting flash messages in partial yields error "undefined method `each' for nil:NilClass"? [duplicate]

Possible Duplicate:
Flash Messages in Partials (Rails 3)

I am doing Michael Hartl's Railstutorial and listing 7.26 adds flash messages to the application layout:

<!DOCTYPE html>
<html>
.
.
.
  <body>
    <%= render 'layouts/header' %>
    <div class="container">
      <% flash.each do |key, value| %>
        <div class="alert alert-<%= key %>"><%= value %></div>
      <% end %>
      <%= yield %>
      <%= render 'layouts/footer' %>
      <%= debug(params) if Rails.env.development? %>
    </div>
    .
    .
    .
  </body>
</html>

This works fine.

However, I tried to clean up this code by creating a _flash.html.erb in my partial folder...

<% flash.each do |key,value| %>
  <%= content_tag(:div, value, class: "alert alert-#{key}") %>
  <!-- <div class="alert alert-<%= key %>"><%= value %></div> -->
<% end %>

...and than using...

<%= render 'partials/flash' %>

...in my application layout all my Rspec tests start failing with the following message for each test:

 Failure/Error: before { visit signup_path }
 ActionView::Template::Error:
   undefined method `each' for nil:NilClass

The key issue seems to be that flash is nil because wrapping my _flash partial in an if statement like this...

<% unless flash.empty? %>
  <% flash.each do |key,value| %>
    <%= content_tag(:div, value, class: "alert alert-#{key}") %>
    <!-- <div class="alert alert-<%= key %>"><%= value %></div> -->
  <% end %>
<% end %>

... yields the same error message about NilClass as above and wrapping it in an if statement like this...

<% if flash %>
  <% flash.each do |key,value| %>
    <%= content_tag(:div, value, class: "alert alert-#{key}") %>
    <!-- <div class="alert alert-<%= key %>"><%= value %></div> -->
  <% end %>
<% end %>

... breaks the flash messages from working (because 'if flash' is always false).

I have two related questions:

  1. Why/how exactly does using the partials/flash solution change the behavior of a rails app?

  2. How to change my partials/flash so it will work?

Thanks!

like image 697
Peter-Jan Celis Avatar asked Nov 25 '12 13:11

Peter-Jan Celis


1 Answers

Set locals with a hash of params/values to pass to the partial

<%= render :partial => "partials/flash", :locals => {:flash => flash} %>
like image 111
adc Avatar answered Sep 22 '22 00:09

adc