6

在我的 Rails 应用程序中,我有以下类型的多级层次结构:

class Vehicle < ActiveRecord::Base end
class RoadVehicle < Vehicle end
class Car < RoadVehicle end
class Buss < RoadVehicle end

然后我有一个引用中间级别的类,如下所示:

class Garage < ActiveRecord::Base
  has_many :road_vehicles
end

在这个简化的示例中,我为车辆表提供了一个类型列以启用单表继承。此外,它包含一个garage_id 列,以启用has_many 关系。当我创建一个新车库并添加汽车和公共汽车时,所有这些都按预期添加到数据库中。但是,当我稍后检索车库对象并检查 road_vehicles 集合时,它是空的。谁能告诉我我做错了什么?

4

1 回答 1

6

在使用单表继承模型设置关联时,您需要参考父模型,以便关联可以推断出表名。所以,在你的Garage课堂上,你需要:

has_many :vehicles

如果要将关联限制为RoadVehicles,可以添加条件:

has_many :vehicles, :conditions => {:type => ['Car', 'Bus']}
于 2010-01-26T00:38:28.120 回答