Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Single Table Inheritance: How to override the value written to the type field

In my system I have STI already defined. Dog inherits from Animal, in the animals table there's a type column with the value "Dog".

Now I want to have SpecialDog inherit from dog, just to modify the behavior slightly in some special case. The data is still the same. I need all the queries that are run through SpecialDog to return the values in the database that have the type Dog.

My problem is that since I have a type column, rails appends WHERE "animals"."type" IN ('SpecialDog') to my query so I cannot get to the original Dog entries. So what I want is to somehow override the value rails uses when it accesses the database through SpecialDog to behave like Dog.

Is there a way to override the value rails use for the type column?

like image 668
davidrac Avatar asked Apr 04 '13 09:04

davidrac


Video Answer


1 Answers

It kind of feels like bad practice to do it this way, but the below code should work as far as I can tell.

def self.sti_name
  "Dog"
end

My other suggestion is to not have SpecialDog inherit from Dog, if possible.

like image 118
Frans Avatar answered Sep 21 '22 10:09

Frans