Rails 3 - 通知和错误 Flash 不能部分呈现 [英] Rails 3 - notice and error flash cannot be rendered in a partial

查看:47
本文介绍了Rails 3 - 通知和错误 Flash 不能部分呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图清理 application.html.erb,通过将布局的部分移动到部分中.我有以下用于处理 Flash 错误/通知的代码:

<% if flash[:notice] %><h3 class="info_box"><%= flash[:notice] %></h3><%结束%><% if flash[:error] %><h3 class="error_box"><%= flash[:error] %></h3><%结束%>

这段代码在 application.html.erb 中运行良好,直到我将它移到一个名为_flash.html.erb"的文件中,并将其替换为以下内容:

<%= render 'layouts/flash' %>

在部分中,闪存哈希不是可识别的对象,并导致当您没想到时,您有一个 nil 对象!"错误.

我已将代码移回 application.html.erb,一切正常.但是我找不到在部分中访问闪存哈希的答案.查看 Rails Guide for "Rendering and Layouts" 我可以看到 render() 有多种方法可以将变量传递到部分中,但我没有弄清楚.有什么想法吗?

解决方案

Goliatone 的解决方案似乎有效,但最终却没有.我发现这对我不起作用的原因是我将部分命名为 _flash.显然,Rails 使用部分的名称(没有 "_" 字符)为部分创建了一个局部变量.所以我有一个变量冲突.一旦我将部分的名称更改为 _flash 以外的其他名称,一切都运行良好.我在这里找到了答案:Rails flash[:notice] always nil

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?

解决方案

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

这篇关于Rails 3 - 通知和错误 Flash 不能部分呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆