Rails 4:Flash 消息在下一页视图中保留



我在布局中使用以下代码来显示两种类型的 Flash 消息:

    <% if !flash[:notice].nil? %>
    <div class="row">
        <div class="flash notice col-xs-12">
            <%= flash[:notice] %>
        </div>
    </div>
    <% end %>
    <% if !flash[:error].nil? %>
    <div class="row">
        <div class="flash error col-xs-12">
            <%= flash[:error] %>
        </div>
    </div>
    <% end %>
    <%= debug(flash[:notice]) %>
    <%= debug(flash[:error]) %>

它们都工作正常,但是每当触发一个时,它仍然会出现一个额外的页面视图。我没有使用任何缓存宝石。

为什么会这样?我该如何解决它?

使用 flash.now 而不是 flash

flash 变量用于redirect之前,并且它保留在结果页面上的一个请求。这意味着如果我们不redirect,而是简单地render页面,则flash消息将保留两个请求:它出现在呈现的页面上,但仍在等待重定向(即第二个请求),因此如果您单击链接,该消息将再次出现。

为了避免这种奇怪的行为,在渲染而不是重定向时,我们使用 flash.now 而不是 flash .

flash.now 对象用于在呈现的页面上显示flash消息。根据我的假设,如果您在意想不到的地方找到一条随机flash消息,您可以通过将flash替换为flash.now来解决它。

最新更新