How to allow custom flash keys in a redirect_to call in Rails 3

后端 未结 2 544
有刺的猬
有刺的猬 2020-12-31 06:11

In Rails 3, you can pass has attributes directly to redirect_to to set the flash. For example:

redirect_to root_path, :notice => \"Something          


        
相关标签:
2条回答
  • 2020-12-31 06:50

    I used the following code, placed in lib/core_ext/rails/action_controller/flash.rb and loaded via an initializer (it's a rewrite of the built-in Rails code):

    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
    

    You can, of course, add more keys besides just :error; check the code at http://github.com/rails/rails/blob/ead93c/actionpack/lib/action_controller/metal/flash.rb to see how the function looked originally.

    0 讨论(0)
  • 2020-12-31 07:09

    In Rails 4 you can do this

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

    and then somewhere

    redirect_to root_path, error: 'Some error'
    

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

    0 讨论(0)
提交回复
热议问题