views:

24

answers:

1

I was wondering, how an association like the following might be done in 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

Essentially, I am trying to enforce that a Person can have one Car or one Truck but cannot have both.

As a secondary, is there a solution where a Person can have many Car or many Truck, but not a mix of both?

Any ideas on what's the way to do this?

+2  A: 

A good time for 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)

The second part of the question is trickier. One approach is to use inheritance on the Person as well:

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
zetetic
Thanks! That points me in the right direction
Zabba