2010-01-25 94 views
6

在我的Rails應用程序,我有以下類型的多層次結構:的has_many多層次結構和單表繼承

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集合時,它是空的。誰能告訴我我做錯了什麼?

回答

6

設置與單個表繼承模型的關聯時,需要引用父模型,以便關聯可以推斷表名。所以,在你Garage類,你需要:

has_many :vehicles 

如果你想給協會限制RoadVehicles,您可以添加條件:

has_many :vehicles, :conditions => {:type => ['Car', 'Bus']}