0

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).

hakunin
  • 4,041
  • 6
  • 40
  • 57
  • For that you have to establish has_many and belongs_to relation b/w car & suvs – Muhammad Ali May 02 '16 at 12:56
  • Your module has to work on non-car models as well? If not, one option would be to query the Car model `Car.where(category: self.category)`. – Uzbekjon May 02 '16 at 13:08

2 Answers2

2

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.

Andrew Schwartz
  • 4,440
  • 3
  • 25
  • 58
0

This should do the trick:

module Categorizable
  def after_save
    # Get the base class. Please note, this will work on 1 level deep STI
    klass = self.type.blank? ? self.class : self.class.superclass

    siblings = klass.where(category: self.category)

    # ...
  end
end
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54