ActiveRecord-连接多张表之单表继承
1. 基本概念
2. 单表继承
# model的定义
class People
# 迁移文件的定义,即关系型数据库的体现
create_table :people, :force => true do |t|
t.column :type, :string
# common attributes
t.column :name, :string
t.column :email, :string
# attributes for type=Customer
t.column :balance, :decimal, :precision => 10, :scale => 2
# attributes for type=Employee
t.column :reports_to, :integer
t.column :dept, :integer
# attributes for type=Manager
# none
end
# 添加人员
boss = Manager.create({name: 'Jobs', email: '[email protected]', dept: 1})
empl = Employee.new({name: 'David', email: '[email protected]', dept: 2})
empl.boss = boss
empl.save
user = Customer.create({name: 'Jim', email: '[email protected]', balance: 100})
2.1 ActiveRecord如何如此简单的提供了单表继承?
2.2 如果一个新加入的开发者使用People添加了人员呢?
god = Person.create({name: 'God', email: '[email protected]'})
2.3 单表继承的优点和缺点
5. 参考
- 《Web开发敏捷之道》第2版#P341-连接多张表