我正在尝试从插件中修补我的Rails(4.2.5)应用程序的 ApplicationController 。 我想将'rescue_from ActiveRecord :: RecordNotFound'添加到我的ApplicationController.Ways我一直试用到现在:
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 :(得分:4)
在这里,我做了同样的事情并测试它对我来说效果很好。以下是我的模块。我已添加到Application 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 将是重定向网址
在application.rb中 - 添加以下行
config.autoload_paths += %W(#{config.root}/lib)
重启服务器....
然后ApplicationController - 包含模块
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
请告诉我如果有任何问题