0

我正在尝试从 gem 扩展 rails 模型。

使用关注我已经能够扩展类方法,但我不能扩展关联included do返回undefined method belongs_to。我认为 Rails 无法正确加载类......

模型引擎中,我正在尝试从我的gem访问它。

这是代码:

# mygem/config/initializers/mymodel_extension.rb
require 'active_support/concern'

module MymodelExtension
  extend ActiveSupport::Concern

  #  included do
  #    belongs_to :another
  #  end

  class_methods do
    def swear
        return "I'm not doing it again"
    end
  end

end

class Myengine::Mymodel
    include MymodelExtension
end

从命令行:

Myengine::Mymodel.swear
# => "I'm not doing it again"

如果我取消注释,included do我会收到此undefined method 'belongs_to' for Myengine::Mymodel:Class (NoMethodError)错误。

4

1 回答 1

2

Myengine::Mymodel类应该继承自ActiveRecord::Base定义belongs_to方法。

ActiveRecord::Base包括一堆模块,其中一个是Associations,在哪里belongs_to association定义。

于 2016-09-23T18:41:33.050 回答