Ruby on rails Rails ActiveRecord协会“;“一个或另一个”;
我想知道,在Rails中如何实现如下关联:Ruby on rails Rails ActiveRecord协会“;“一个或另一个”;,ruby-on-rails,activerecord,associations,Ruby On Rails,Activerecord,Associations,我想知道,在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 :tru
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
class-Car
本质上,我试图强制一个人可以拥有一辆车或一辆卡车,但不能同时拥有这两辆车
作为第二种解决方案,是否有一种解决方案,一个人可以拥有多辆汽车
或多辆卡车
,但不能两者兼而有之
有什么办法可以做到这一点吗?这是一个好时机
class车辆
问题的第二部分比较棘手。一种方法是对人使用继承:
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
class-Personclass 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