a.barbieri a.barbieri - 2 months ago 32
Ruby Question

Undefined method belongs_to usign Rails concern, why?

I'm trying to extend a rails model from a gem.

Using concern I've been able to extend class methods but I cannot extend associations.

included do
returns
undefined method belongs_to
. I think Rails cannot load the class properly...

The model is in a engine and I'm trying to access it from my gem.

Here is the code:

# 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


From command line:

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


If I uncomment the
included do
I get this
undefined method 'belongs_to' for Myengine::Mymodel:Class (NoMethodError)
error.

Answer

Myengine::Mymodelclass should inherit from ActiveRecord::Base to have belongs_to method defined.

ActiveRecord::Base includes bunch of modules, one of which is Associations, where belongs_to association is defined.

Comments