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

时间:2010-10-03 05:51:21

标签: redirect ruby-on-rails-3

在Rails 3中,您可以将has属性直接传递给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 => {}中指定它?

2 个答案:

答案 0 :(得分:28)

在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

答案 1 :(得分: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处的代码,了解该功能最初的效果。