2011-01-06 120 views
72

我在我的控制器中執行一些異常處理,當出現異常時:create action,我將渲染到:new action並顯示一條flash消息。爲什麼flash消息不會消失?

一切工作正常,我可以看到當異常捕獲閃光燈的消息,但是當我重定向到(handly點擊)其他頁,閃光燈消息還在這裏。然後我重定向到另一個頁面(第二次點擊),消息可能消失。

任何人知道是什麼原因?

我的控制器代碼:

class MessagesController < ApplicationController 
    rescue_from Exception, :with => :render_new 

    def new 
    end 

    def create 
    end 

private 
    def render_new 
    flash[:alert] = t("uploading_error") 
    render :action => :new 
    end 
end 

我的佈局代碼(Haml的):

%body 
    #content 
    - unless flash[:alert].blank? 
     #alert= flash[:alert] 

回答

145

替換

flash[:alert] = t("uploading_error") 

flash.now[:alert] = t("uploading_error") 

並查看這是否是您期望的結果?

flash[:alert]將留在下一頁(因此它只會在第二次重定向時消失);但flash.now[:alert]只會顯示當前頁面。

+0

優秀的解決方案和紐帶!謝謝你zabba! – 2011-01-06 10:58:56

+1

現在我知道更多關於閃光和flash.now。因此,如果我使用redirect_to而不是渲染,使用閃光燈也不會有問題。 – 2011-01-06 12:20:39

+1

僅供參考:鏈接已中斷。但是沒有看到鏈接,我不得不承認我很好奇爲什麼flash.now [:alert]不是默認的。 – Trip 2012-03-14 15:17:58

45

在flash.now和flash之間做出決定是一件痛苦的事情,在我的經驗中非常脆弱。我使用普通閃光燈,然後修改顯示閃光的部分,以便在用戶看到閃光燈後刪除每個閃光燈的內容。我覺得這是更好,因爲

一)你不必去想它

二)「已經在用戶看到了嗎?」 (即「閃爍部分已渲染?」)是決定是否清除閃存的最佳標準,而不是您的應用中的任何邏輯。

我的閃光部分看起來像這樣 - 我也用了一下jQuery的,只是爲了突出閃爍(即使其閃爍黃色第二):

<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> 
1

即使這不工作.... ..某些類型的異常,如語法錯誤......將阻止任何類型的cookie,閃存或參數從控制器傳輸到視圖。您唯一的選擇是使用會話密鑰,然後在顯示錯誤後清除它。

用語法錯誤試試你的解決方案......你應該看到你的消息不會出現在重定向頁面中,除了使用會話密鑰以外的其他內容。

30

另一種方法是在局部像這樣結束使用flash.clear

<% if !flash.empty? %> 
    <div class="flash-messages-container"> 
    <% flash.each do |name, msg| %> 
     <% if msg.is_a?(String) && [:success, :info, :error, :warning].include?(name) %> 
     <div class="flash-message" data-type="<%= name %>" > 
      <%= msg %> 
     </div> 
     <% end %> 
    <% end %> 
    </div> 
    <% flash.clear %> 
<% end %> 
1

以前我同樣的問題,但現在通過這個解決:
在你的代碼試試這個

<script type="text/javascript"> 
    $(document).ready(function(){ 
    setTimeout(function(){ 
    $('#flash').fadeOut(); 
    }, 2000); 
    }) 
</script>