Rails 3 - 通知和错误闪存无法部分渲染

发布于 2024-12-14 01:33:19 字数 747 浏览 5 评论 0原文

我试图通过将部分布局移动到部分布局来清理 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随波逐流 2024-12-21 01:33:19

戈利亚托内的解决方案看似有效,但最终却没有成功。我发现这对我不起作用的原因是我将我的部分命名为 _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

千里故人稀 2024-12-21 01:33:19

您可以在布局中放置对 flash 的条件检查,如果存在,则渲染部分:

<%= render 'layouts/flash' unless flash.nil?%>

然后,如果存在,它将按预期渲染。

You can place the conditional check for flash in the layout, and if it exists then render the partial:

<%= render 'layouts/flash' unless flash.nil?%>

Then, if it exists it will get rendered as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文