很适合
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)
问题的第二部分比较棘手。一种方法是对个人也使用继承权:
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