Object#type Errors with Single Table Inheritance
Everybody probably already know this but what the hell. I was working on some code recently using Single Table Inheritance and was getting errors in the console and log when comparing the type field.
Before I get into the error itself and what I’m doing to correct it, a little background on Single Table Inheritance. Suppose you have employees in your database and you have two employee types; managers and staff.
You might have the following model objects:
class Manager < ActiveRecord::Base
end
class Staff < ActiveRecord::Base
end
And in the database, you’d have two separate tables; one for managers and one for staff. This is fine if the Manager table and the Staff table differ greatly from one another, but if they are identical with the exception of the type (Manager or Staff) then they can be combined in one table and be referenced in Rails using Single Table Inheritance.
This is done by having one class that Manager and Staff inherit from:
class Employee < ActiveRecord::Base
end
class Manager < Employee
end
class Staff < Employee
end
Now you can have one table, Employee, with a type column that differentiates that two. For example:
| id | type | full_name | phone_number |
|---|---|---|---|
| 1 | Staff | Joe Jukem | 5035551212 |
| 2 | Manager | Joe Blow | 7025551212 |
Now here is where the problem comes in. Apparently “type” shouldn’t be used in your code. So when you’re doing something like this:
x = Employee.find :first
if x.type == Manager
do something here
end
You’ll get a message that reads: warning: Object#type is deprecated; use Object#class instead. Now, obviously, the fix is to use something like this:
x = Employee.find :first
if x.class == Manager
do something here
end
That works, but I like the more readable version using the is_a? method. For example:
x = Employee.find :first
if x.is_a?(Manager)
do something here
end