Rails ActiveRecord关联“一个或另一个”

时间:2010-10-09 04:33:01

标签: 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 :truck
end

基本上,我试图强制Person可以有一个Car 一个Truck但不能同时拥有这两个。{/ p>

作为辅助解决方案,是否存在Person可以 Car Truck的解决方案,但不是两者兼而有之?

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分: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