a.barbieri a.barbieri - 1 year ago 125
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
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"


class Myengine::Mymodel
include MymodelExtension

From command line:

# => "I'm not doing it again"

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download