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
質問
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!
解決
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