2010-10-09 34 views
1

我在想,怎麼樣以下的關聯可能在Rails中進行:從本質上講Rails的ActiveRecord的關聯「一個或另一個」

class Car < ActiveRecord::Base 
    belongs_to :person 
end 

class Truck < ActiveRecord::Base 
    belongs_to :person 
end 

class Person < ActiveRecord::Base 
    #How to do the association as below? 
    has_one :car or :truck 
end 

,我試圖執行一個Person可以有一個Car一個Truck但不能同時擁有。

作爲次要的,是有一個解決方案,其中一個Person可以有許多Car許多Truck,但不是兩者的組合?

有關如何做到這一點的任何想法?

回答

3

的好時機Single Table Inheritance

class Vehicle < ActiveRecord::Base 
    belongs_to :person 
end 

class Car < Vehicle 
    # car-specific methods go here 
end 

class Truck < Vehicle 
    # truck-specific methods go here 
end 

class Person < ActiveRecord::Base 
    has_one :vehicle 
end 

person = Person.new 
person.vehicle = Car.new # (or Truck.new) 

問題的第二部分是棘手。一種方法是在Person上也使用繼承:

class Person < ActiveRecord::Base 
    has_many :vehicles 
end 

class TruckDriver < Person 
    def build_vehicle(params) 
    self.vehicles << Truck.new(params) 
    end 
end 

class CarDriver < Person 
    def build_vehicle(params) 
    self.vehicles << Car.new(params) 
    end 
end 
+0

謝謝!這使我指向了正確的方向 – Zabba 2010-10-10 06:59:00