开发者

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

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

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

However, this only work开发者_StackOverflow中文版s with the :alert and :notice keys; if you want to use custom keys, you have to use a more verbose version:

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

Is there any way to make it so that custom keys (such as :error, above) can be passed to redirect_to without specifying it in :flash => {}?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜