Domanda

I'm creating 4 ActiveRecord models that all inherit from the same base class. Currently, each of the 4 models has a belongs to relationship defined like this:

belongs_to :parent, :class_name => 'ChildClass1'

I'd like to pull this out into the base class with something along the lines of:

belongs_to :parent, :class_name => self.class_name

Any ideas on how to do this?

Thanks!

È stato utile?

Soluzione

You can try using the inherited hook:

class BaseClass
  def self.inherited(child_class)
    child_class.class_eval do
      belongs_to :parent, :class_name => child_class.name
    end
    super
  end
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top