0

我想从一个宝石扩展一个轨道模型。未定义的方法belongs_to usign Rails关心,为什么?

使用关注我已经能够延长类方法但我不能延长协会included do返回undefined method belongs_to。我认为Rails可以正确载入类...

模型处于引擎,我想从我的宝石访问它。

下面是代码:

# 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)错误。

回答

2

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

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

+0

虽然有一个问题:如果我做'类Spina :: PagePart

+0

@ a.barbieri没有这样的事情,比如在Ruby中扩展一个类。你正在继承。在你的类中定义的任何方法(如果有的话,它们在'AR :: Base'中定义)将优先,所以不用担心 –

相关问题