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:
Why/how exactly does using the partials/flash solution change the behavior of a rails app?
How to change my partials/flash so it will work?
Thanks!
Set locals with a hash of params/values to pass to the partial
<%= render :partial => "partials/flash", :locals => {:flash => flash} %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With