微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Rails - 包含一个模块而不使用包含这个词

如何解决Rails - 包含一个模块而不使用包含这个词

我注意到在审计的 gem 中你可以这样做:

class User < ActiveRecord::Base
  # All fields
  # audited

  # Single field
  # audited only: :name

  # Multiple fields
  # audited only: [:name,:address]

我试图复制这种行为,但运气不佳,我在这里使用说明来扩展我的模块:https://stackoverflow.com/a/9200191/312342

这是我的课:

class Thing < ApplicationRecord
  audited only: :name
end

我的模块:

module Audited
  extend ActiveSupport::Concern
    
    def ClassMethods
      def audited(options = {})
        class_attribute :audited_options
        self.audited_options = options
        after_save :audit
      end
    end

    def audit
      puts self.changed_attributes
      puts self.audited_options
    end
end

::ActiveRecord::Base.send(:include,Audited)

我得到的错误(仅在第一次加载时,然后错误停止,但模块仍然没有输出

NoMethodError (undefined method `audited' for #<Class:0x00007fae51b15ab0>):

解决方法

只有在执行文件时,您的模块才会包含在 ActiveRecord::Base 中。假设您使用 Rails 自动加载,它仅在调用 Audited 时执行。

您需要在加载过程中的某处(初始化程序)需要该文件或执行 ::ActiveRecord::Base.send(:include,Audited)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。