Rails STI and the setting of the "type" string
Asked Answered
P

2

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.

Prevenient answered 1/2, 2011 at 1:54 Comment(0)
P
14

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

Pierrette answered 1/2, 2011 at 2:2 Comment(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.Leer
@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)?Fairweather
E
6

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

Etalon answered 21/7, 2011 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.