如何在Rails 3中的redirect_to调用中允许自定义闪存键

Mic*_*ley 15 redirect ruby-on-rails-3

在Rails 3中,您可以直接传递has属性redirect_to来设置flash.例如:

redirect_to root_path, :notice => "Something was successful!"
Run Code Online (Sandbox Code Playgroud)

但是,这仅适用于:alert:notice键; 如果要使用自定义键,则必须使用更详细的版本:

redirect_to root_path, :flash => { :error => "Something was successful!" }
Run Code Online (Sandbox Code Playgroud)

是否有任何方法可以将自定义键(例如:error,上面)传递给redirect_to它而不指定它:flash => {}

wot*_*oto 28

在Rails 4中,您可以执行此操作

class ApplicationController < ActionController::Base
  add_flash_types :error, ...
Run Code Online (Sandbox Code Playgroud)

然后在某个地方

redirect_to root_path, error: 'Some error'
Run Code Online (Sandbox Code Playgroud)

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


Mic*_*ley 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
Run Code Online (Sandbox Code Playgroud)

当然,您可以添加更多按键:error; 检查http://github.com/rails/rails/blob/ead93c/actionpack/lib/action_controller/metal/flash.rb上的代码,了解该函数最初的外观.