STI of ActiveRecord in Rails

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     |                |
+--------------------------+--------------+------+-----+----------+----------------+

Code

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

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

just this, and we can verify it in console:

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

Concerns

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
end
class Administrator < Post
end

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

Referrence

http://ihower.tw/rails3/activerecord-others.html

发表评论

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