1

我有以下型号:如何在继承rails模型时写入不同的表格?

class Building < ActiveRecord::Base;end 

class Department < Building;end 

class Organization < Building;end 

当我创建部门和组织,并得到所有部门

2.1.5 :008 > Department.all.count 
(0.5ms) SELECT COUNT(*) FROM "buildings" 
=> 2 

我想在这种情况下

2.1.5 :008 > Department.all.count 
(0.5ms) SELECT COUNT(*) FROM "departments" 
=> 1 

2.1.5 :008 > Organization.all.count 
(0.5ms) SELECT COUNT(*) FROM "organizations" 
=> 1 

2.1.5 :008 > Buildings.all.count 
(0.5ms) SELECT COUNT(*) FROM "buildings" 
=> 2 

让我怎样才能去做?

+4

继承在rails中创建了一种称为单表继承的功能:http://guides.rubyonrails.org/association_basics.html#single-table-inheritance – Anthony

+0

我认为这不是你想要做的事情。 @Anthony将你带入单表继承(STI) – Sean

+0

的正确轨道,换句话说,当你继承你没有创建多个表时。 –

回答

0

使用STI。有一个名为“类型”的列名为建筑物的表。让新类扩展Building类。每个班级可以有不同的关系。您将能够实例化Building并获取由该类型定义的类或直接实例化所需的类。

+0

谢谢,我现在看到我的问题并不清楚!我需要通过使用'type' – Roman