Flash Messages in Partials (Rails 3)
I have a partial,
_flash.html.haml
- flash.each do |type, value|
.flash{ :class => type.to_s }
= value
Which I'm rendering from a view using
=render :partial开发者_Go百科 => "flash"
Which complains that the flash hash is nil/undefined. However, when I do this:
=render :partial => "flash", :locals => {:flash => flash}
It works.
Why doesn't the partial have access to the flash message?
In previous versions of Rails (Rails 2), the default local variable would look for an instance variable with the same name as the partial in the parent.
Given your example since the partial is named _flash
it would automatically pass the instance variable flash as a local to the partial. Thus you would have access to it. This behavior was deprecated in 2.3 and has been removed in Rails 3.0.
This means that you always have to explicitly pass all instance variables as locals
, even flash
, just as you wrote in your latter example.
<%= render :partial => "flash", :locals => {:flash => flash} %>
This has nothing to do with flash
per say, flash
is a instance variable just as any other.
Because your partial is named "_flash", you should have the :object local to specify variable flash inside the partial.
Change your partial name and you will be able to use flash inside, for example:
= render "show_flash_names"
Every partial is rendered in a context which contains an implicit local variable whose name is that of the partial (excluding the leading underscore). So a _flash.html.haml
partial will always have a flash
local which shadows ActionView::Base#flash
. If you don't pass an argument to the partial (either via :locals => {:flash => flash}
or :object => flash
, the value of the local is simply nil
.
As suggested, you can rename the partial to avoid the name conflict, or use the more verbose calls to render
.
This is an annoying misfeature of Rails, in my opinion, and I'd like to see it changed.
This will also achieve your desired result:
<%= render partial: "flash", object: flash %>
The flash
object is being passed to the admin/shared/flash
partial as flash
, since the partial is called flash
. You'll have access to the flash
object from within the partial as you'd expect it in any regular view.
精彩评论