我想知道如何在Rails中完成以下关联:
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
但不能同时拥有这两个。{/ p>
作为辅助解决方案,是否存在Person
可以多 Car
或多 Truck
的解决方案,但不是两者兼而有之?
关于如何做到这一点的任何想法?
答案 0 :(得分:3)
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