Rails的flash[:notice]总是为空。

8

我不明白为什么我的Rails视图无法识别flash[:notice]或flash[:error]。 我一直收到有关渲染部分视图的以下错误。 具体错误是:

ActionView :: Template :: Error(您有一个空对象,而您没有期望它! 您可能希望有一个Array实例。 发生错误时正在评估nil。 []):

在我的控制器中:

  def index
    @organisms = Organism.all
    flash[:error] = "test"
    flash[:notice] = "test"
    respond_to do |format|
      format.html
      format.json  { render :json => @organisms }
    end
  end

在我的index.html.erb文件中,我通过以下方式呈现一个局部视图:
<%= render "shared/flash" %>

这个局部视图包含以下代码。
<div id="flashes">

  <% if flash[:notice] %>
    <p id="flash_notice" class="messages notice"><%= flash[:notice] %></p>
    <%= javascript_tag "$('#flash_notice').effect('highlight',{},1000);" %>
  <% end %>
  <% if flash[:error] || flash[:errors] %>
    <p id="flash_errors" class="messages errors"><%= flash[:error] || flash[:errors] %></p>
    <%= javascript_tag "$('#flash_errors').effect('highlight',{},1000);" %>
  <% end %>

  <% flash[:error] = flash[:errors] = flash[:notice] = nil %>
</div>

然而,如果我在呈现局部视图时加入<%= notice %>,它会呈现出通知。

如果我将局部代码复制到index.html.erb文件的顶部,则可以正确呈现。因此,我认为我可能没有正确呈现局部视图?

非常感谢任何帮助。谢谢!


1
你缺少了关键部分:如何渲染局部视图。另外,不要在底部取消 flash。Rails 已经为您处理了这个问题。 - Ryan Bigg
谢谢提供信息。我已经添加了如何呈现局部的代码。 - Phillip Whisenhunt
1
你不需要这样做:<% flash[:error] = flash[:errors] = flash[:notice] = nil %> - Mohit Jain
你是否在某处执行了 flash = nil?错误指向哪一行?flash[:errors] 是什么 - 你没有在任何地方设置它的值。 - Zabba
2个回答

26

不要将你的局部文件命名为flash。Ruby on Rails会创建一个与局部文件同名的本地变量。在你的情况下,会创建一个名为flash的本地变量。

将你的局部文件重命名为除flash之外的其他名称,这样应该就可以了。

此外,在你的局部文件底部不需要将flash设置为nil。让Rails自动处理即可。


1
给部分命名为“_flash”是我的问题。感谢罗伯特指出这一点。我永远不会想到的。 - Don Leatham

2
你需要将flash传递给partial:
<%= render 'shared/flash', flash: flash %>

或稍微长一点:

<%= render partial: 'shared/flash', locals: { flash: flash } %>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接