Search code examples
ruby-on-railsactiverecordrails-activerecordsingle-table-inheritance

ActiveRecord single table inheritance - how to get root model?


I have a model using single table inheritance and a concern that should work on any model.

Consider this example:

class Car
  acts_as_categorizable
end

class Suv < Car; end

module Categorizable
  def after_safe
    siblings = this.class.where(category: self.category)
    #... do something with the siblings
  end
end

Now if I have an Suv and manipulate its category, the siblings line will only find the other Suv cars in that category, but I need to find all cars in that category.

I don't want to hardcode this, so given a Suv class, I need to find its root model (Car).


Solution

  • There's actually already a method for this; base_class. So Suv.base_class should return Car, and any subclass of Suv will also return Car with this method.