2010-10-03 58 views
11

在Rails 3中,您可以將屬性直接傳遞給redirect_to來設置閃存。例如:如何在Rails 3中的redirect_to調用中允許自定義閃存密鑰

redirect_to root_path, :notice => "Something was successful!" 

然而,這隻能與:alert:notice鍵;如果你想使用自定義的按鍵,你必須使用一個更詳細的版本:

redirect_to root_path, :flash => { :error => "Something was successful!" } 

有沒有什麼辦法讓這個自定義鍵(如:error,以上)可以傳遞給redirect_to沒有具體說明在:flash => {}

回答

25

在Rails 4,你可以做到這一點

class ApplicationController < ActionController::Base 
    add_flash_types :error, ... 

,然後某處

redirect_to root_path, error: 'Some error' 

http://blog.remarkablelabs.com/2012/12/register-your-own-flash-types-rails-4-countdown-to-2013

+0

真棒!將其標記爲接受的答案,因爲它應該用於未來。 – 2013-09-05 17:09:32

+0

即時通訊運行到一個問題,我稱之爲閃光類型:登錄,但我也有一個輔助方法登錄從「魔法寶石。」。也許增加閃光燈類型,目前還不是很好? – dtc 2015-03-22 11:10:29

+0

談論性能或實現相同行爲的正確方法,最好的方法是:** 1.-添加新的flash類型**,如'add_flash_types:error,...'或** 2.-在Flash對象**中添加新的哈希,就像':flash => {:error =>「哦,不! ''? – 2017-07-12 22:15:41

8

我用下面的代碼,放置在lib/core_ext/rails/action_controller/flash.rb和加載通過初始化(它是內置的Rails代碼的重寫):

module ActionController 
    module Flash 
    extend ActiveSupport::Concern 

    included do 
     delegate :alert, :notice, :error, :to => "request.flash" 
     helper_method :alert, :notice, :error 
    end 

    protected 
     def redirect_to(options = {}, response_status_and_flash = {}) #:doc: 
     if alert = response_status_and_flash.delete(:alert) 
      flash[:alert] = alert 
     end 

     if notice = response_status_and_flash.delete(:notice) 
      flash[:notice] = notice 
     end 

     if error = response_status_and_flash.delete(:error) 
      flash[:error] = error 
     end 

     if other_flashes = response_status_and_flash.delete(:flash) 
      flash.update(other_flashes) 
     end 

     super(options, response_status_and_flash) 
     end 
    end 
end 

你可以,當然,增加更多的按鍵除了剛纔:error ;查看http://github.com/rails/rails/blob/ead93c/actionpack/lib/action_controller/metal/flash.rb的代碼,查看最初的功能。

相關問題