2017-10-12 22 views
0

我试图从插件修补我的Rails(4.2.5)应用程序的ApplicationController。 我要添加 'rescue_from的ActiveRecord :: RecordNotFound' 我ApplicationController.Ways我已经试过至今:Rails将“rescue_from”方法从补丁//插件添加到应用程序控制器

1.

module ApplicationControllerPatch 
      def self.included(base) 
      base.class_eval do 
       rescue_from ActiveRecord::RecordNotFound do |e| 
        redirect_to root_path 
       end 
      end 
     end 
    end 

ApplicationController.send(:include, ApplicationControllerPatch) 

2.

module ApplicationControllerPatch 
    def self.included(base) 
     base.send(:include, InstanceMethods) 
     base.class_eval do 
      rescue_from ActiveRecord::RecordNotFound, with: :not_found 
     end 
    end 
    module InstanceMethods 
     def not_found 
      redirect_to root_path 
     end 
    end 
end 

ApplicationController.send(:include, ApplicationControllerPatch) 
  • 解在此堆栈溢出链接: How do I require ActiveSupport's rescue_from method?

  • 直到现在,似乎没有任何方法可行。 请提供任何解决方案或帮助纠正上述代码中是否有错误。

    +0

    只包含一个模块在ApplicationController中,而不是试图猴补丁它从外面。否则,你不得不担心monkeypatch执行的时间。 – max

    +0

    我无法更改核心Rails应用程序中的代码,因此需要猴子补丁。 – user8544663

    回答

    4

    在这里,我做了同样的事情,并测试它对我来说效果很好。以下是我的模块。我已经加入到应用的lib/exception_data_redirection

    module ExceptionDataRedirection 
        extend ActiveSupport::Concern 
        included do 
        rescue_from ActiveRecord::RecordNotFound do |exception| 
         redirect_to items_path 
        end 
        end 
    end 
    

    items_path将重定向URL

    在application.rb中 - 添加以下代码行

    config.autoload_paths += %W(#{config.root}/lib) 
    

    重新启动服务器。 ...

    Then ApplicationController - include the mo独乐

    include ExceptionDataRedirection 
    

    这工作就像一个魅力,你可以这样做也

    module ExceptionDataRedirection 
    
        def self.included(base) 
        base.class_eval do 
         rescue_from ActiveRecord::RecordNotFound do |exception| 
         redirect_to items_path 
         end 
        end 
        end 
    end 
    

    请让我知道,如果有任何问题

    相关问题