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

1

7

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?

Darlleen answered 4/4, 2013 at 9:46 Comment(2)
Are you saving any dogs as SpecialDog? Or are all dogs Dog, but they're sometimes special?Elburr
In the database they are always 'Dog'Darlleen
E
13

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.

Elburr answered 4/4, 2013 at 10:39 Comment(1)
not working anymore??? i have the same case, ruby 2.0.0, rails 3.0.10, no success using it.Olenolin

© 2022 - 2024 — McMap. All rights reserved.