6

I think I need to use STI in Rails.

Here's my class:

class Person < ActiveRecord::Base
end

class Landlord < Person
end

and the people table has a :type column that's a string.

So, what I expect is to see in the table, is that every row that is a Person has the type set to "Person" and every Landlord has the type set to "Landlord". However, that's not what I see. Each Landlord has the type set to "Landlord", but all the Person have their type set to nil. This very well could be the way that rails works, but I was just looking for some confirmation.

user229044
  • 232,980
  • 40
  • 330
  • 338
TheDelChop
  • 7,938
  • 4
  • 48
  • 70

2 Answers2

13

This is, indeed, how STI works. The base class has a type of NULL in the database (or nil in ruby).

Jeff Paquette
  • 7,089
  • 2
  • 31
  • 40
  • 2
    @ioquatix because as the answer says, the base class type is set to null. Typically, you should have `class Person`, with subclasses `Tenant` and `Landlord`. The parent class should hold methods/validations that apply to it and its subclasses. While Rails looks at the subclass name and marks it as the type. – onebree Nov 06 '15 at 21:57
  • @ioquatix Perhaps either to differentiate between the base class and the subclasses, or because creating an object of a regular class shouldn't require setting a type column (only creating objects of a subclass should require a type column)? – Magne Mar 21 '17 at 15:12
6

You can solve this if you want by adding the type column with a default value of "Person".

Ariejan
  • 10,910
  • 6
  • 43
  • 40