【问题标题】:proper way of extending ActiveRecord::Base扩展 ActiveRecord::Base 的正确方法
【发布时间】:2011-05-28 22:28:16
【问题描述】:

我通过以下方式扩展了ActiveRecord::Base 类:

  • 我在lib下做了一个目录,我们现在叫它foo
  • 编写的模块提供了额外的方法has_many_bidirectionalActiveRecord::Base 类中具有双向has_many 关系
  • lib/foo/active_record.rb:

    module Foo
      module ActiveRecord
        autoload :Associations, 'active_record/associations'
        autoload :Base, 'active_record/base'
      end
    end
    
  • lib/foo/active_record/base.rb:

    module Foo
      module ActiveRecord
        module Base
          def self.included(base)
            base.class_eval do
              include Associations
            end
          end
        end
      end
    end
    
  • 当然还有lib/foo/active_record/associations.rb中的真实代码:

    module Foo
      module ActiveRecord
        module Associations
    
          def self.included(base)
            base.extend(ClassMethods)
          end
    
          module ClassMethods
            def has_many_bidirectional(...)
              # ...
            end
          end
        end
      end
    end
    
  • 扩展config/environment.rb中的ActiveRecord::Base类,在配置文件末尾添加如下代码:

    ActiveRecord::Base.class_eval do
      include Foo::ActiveRecord::Base
    end
    
  • 通过这种方式,Rails 正确地包含在我的模块中,我可以毫无问题地使用它

  • 直到我想观察一个扩展类,因为在config/environment.rbconfig.active_record.observers 部分是之前扩展部分,而可观察类不知道那时关于新方法的任何信息。

产生以下错误:

/Library/Ruby/Gems/1.8/gems/activerecord-2.3.10/lib/active_record/base.rb:1998:in `method_missing': undefined method `has_many_bidirectional' for #<Class:0x1032f2fc0> (NoMethodError)
        from .../app/models/user.rb:27

我的问题是,扩展ActiveRecord::Base 类的正确方法是什么? (我不想在User 类中使用回调方法。)

我真的必须在lib 目录下创建一个gem而不是一个模块来获得这个功能吗?

谢谢!

【问题讨论】:

  • has_many_bidirectional 是什么意思?
  • 模型之间的双向连接(例如友谊)

标签: ruby-on-rails activerecord observer-pattern extending


【解决方案1】:

据我了解,最好的方法是使用生成器创建一个插件:

./script/generate plugin has_many_bidirectional

通过这种方式,Rails 会将它包含在观察者部分之前。一个很好的教程可以找到here

我以前的所有代码都可以很容易地采用这种方式。

【讨论】:

  • 教程链接不再可用,至少对我来说是这样。据我通过检查链接可以得出的结论,这是对 Rob Orsini 的“Rails Cookbook”一书的参考,第 14 章“使用插件扩展 Rails”,“使用acts_as 扩展 Active Record”部分。
猜你喜欢
  • 2015-11-14
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多