Rails 3 - 通知和错误闪存无法部分渲染
我试图通过将部分布局移动到部分布局来清理 application.html.erb
。我有以下用于处理 Flash 错误/通知的代码:
<div id="flash">
<% if flash[:notice] %>
<h3 class="info_box"><%= flash[:notice] %></h3>
<% end %>
<% if flash[:error] %>
<h3 class="error_box"><%= flash[:error] %></h3>
<% end %>
</div>
此代码在 application.html.erb
中运行良好,直到我将其移至名为“_flash.html.erb
”的文件中>”并将其替换为以下内容:
<%= render 'layouts/flash' %>
在部分中,闪存哈希不是可识别的对象,并导致“当您没有预料到时,您有一个零对象!”错误。
我已将代码移回 application.html.erb ,一切都很好。但我找不到访问部分闪存哈希的答案。查看 Rails 指南的“渲染和布局”,我可以看到 render() 有多种方法可以将变量传递到局部,但我没有成功地弄清楚它。有什么想法吗?
I was trying to clean up application.html.erb
, by moving parts of the layout into partials. I had the following code for handling flash errors/notifications:
<div id="flash">
<% if flash[:notice] %>
<h3 class="info_box"><%= flash[:notice] %></h3>
<% end %>
<% if flash[:error] %>
<h3 class="error_box"><%= flash[:error] %></h3>
<% end %>
</div>
This code worked fine in application.html.erb
, until I moved it into a file called "_flash.html.erb
" and replaced it with the following:
<%= render 'layouts/flash' %>
In the partial the flash hash was not a recognized object and causes a "You have a nil object when you didn't expect it!" error.
I've move the code back to application.html.erb and all is good. But I couldn't find an answer for accessing the flash hash within a partial. Looking at the Rails Guide for "Rendering and Layouts" I can see that there are various ways for render()
to pass variables into the partial, but I was unsuccessful in figuring it out. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
戈利亚托内的解决方案看似有效,但最终却没有成功。我发现这对我不起作用的原因是我将我的部分命名为
_flash
。显然,Rails 使用部分的名称(不带"_"
字符)为部分创建了一个局部变量。所以我遇到了变量冲突。一旦我将部分名称更改为_flash
以外的名称,一切都会完美运行。我在这里找到了答案: Rails flash[:notice] 始终为零Goliatone's solution seemed to work, but in the end it didn't. I found out that the reason this was not working for me was that I had named my partial
_flash
. Apparently Rails creates a local variable for the partial using the partial's name (without the"_"
character.) So I had a variable clash. As soon as I change the name of the partial to something other than_flash
everything worked perfectly. I found the answer here: Rails flash[:notice] always nil您可以在布局中放置对 flash 的条件检查,如果存在,则渲染部分:
然后,如果存在,它将按预期渲染。
You can place the conditional check for flash in the layout, and if it exists then render the partial:
Then, if it exists it will get rendered as expected.