【问题标题】:Can't access model from inside ActionController method added by a Rails engine无法从 Rails 引擎添加的 ActionController 方法内部访问模型
【发布时间】:2011-10-02 09:10:35
【问题描述】:

我正在开发要打包为 gem 的 Rails 引擎。在我的引擎的主模块文件中,我有:

module Auditor
  require 'engine' if defined?(Rails) && Rails::VERSION::MAJOR == 3
  require 'application_controller'
end

module ActionController
  module Auditor
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      def is_audited
        include ActionController::Auditor::InstanceMethods
        before_filter :audit_request
      end   
    end 

    module InstanceMethods
      def audit_request
        a = AuditorLog.new
        a.save! 
      end   
    end 
  end
end

ActionController::Base.send(:include, ActionController::Auditor)

其中 AuditorLog 是引擎也提供的模型。 (我的意图是使用此引擎将“is_audited”添加到应用程序的控制器中,这将导致请求详细信息的审计日志记录。)

我遇到的问题是,当从使用引擎的应用程序调用此代码时,无法访问 AuditorLog 模型。看起来 Ruby 认为它应该是 ActionController 中的一个类:

NameError(未初始化的常量 ActionController::Auditor::InstanceMethods::AuditorLog)

而不是我的引擎中的模型。

谁能指出我正确的方向?这是我第一次创建引擎并尝试将其打包为 gem;我已经搜索了这方面的例子,但运气不佳。我将这个功能添加到 ActionController 类的方法是基于 mobile_fu 所做的,所以如果我做错了,请告诉我。

【问题讨论】:

  • AuditorLog 在哪里定义?当你做::AuditorLog时它是否有效?

标签: ruby-on-rails ruby rubygems rails-engines


【解决方案1】:

使用 ::AuditorLog 访问 ActiveRecord 类(除非您将它放在模块或命名空间中,在这种情况下您需要包含模块名称)。

【讨论】:

  • 完美,这很容易。谢谢杰里米!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
相关资源
最近更新 更多