STI of ActiveRecord in Rails

By | 2013 年 12 月 25 日

STI, Single Table Inheritance, supported by ActiveRecord in rails to let us build the models’ hierarchy on a single data table.

Model description

For example, we have a User model, and have an Administrator model, which inherit from User. we can build just one table named ‘user’, and make sure there is a column named ‘type’ and of string type in the User table. like below:

mysql>describe 'user';
| Field                    | Type         | Null | Key | Default  | Extra          |
| id                       | int(11)      | NO   | PRI | NULL     | auto_increment |
| type                     | varchar(255) | YES  |     | NULL    |                |
| name                     | varchar(255) | YES  |     | NULL     |                |


then, we can writing following code to have a look of STI:

class User < ActiveRecord::Base
    validates_presence_of :name
class Administrator < User

just this, and we can verify it in console:

admin = Administrator.create( :name => "admin")
admin.type # "Administrator" # 1


the STI is enabled by default, and so the 'type' in table is likely reserved for STI and we can not using it for other purpose;
and another problem is that if the shared columns are not so much in the model hierarchy, it's a waste using STI, we prefer to setup another table for the child model.
Luckily, we can disable this feature in a table that not using this feature. by doing this:

class User < ActiveRecord::Base
    self.abstract_class = true
    validates_presence_of :name
class Administrator < ActiveRecord::Base

Then the 'type' columns in User can be used at our will and there must another table for Administrator alone.



电子邮件地址不会被公开。 必填项已用*标注