Let’s say I have a car table that has many passengers so obviously the
passenger table will have a foreign key to car. The Car model has_many
Passengers. A car can have one and only one driver. What’s the best
way to model this relationship?
Hand coded get and set driver methods in the car class with one of the
following keys.
- a flag in the passenger table noting the passenger as driver
- a passenger foreign key in car to note driver
Extend passenger to make a Driver model and do either:
-
Car belongs_to Driver
-
Car has_one Driver
Or something else?
Thanks!
I would do:
Passengers belong_to Car
Car has_many Passengers
Car has_one Driver, :class => Passenger
Dieter L.
http://www.coder2000.ca
On Mon, May 10, 2010 at 8:52 AM, Dieter L. [email protected]
wrote:
I would do:
Passengers belong_to Car
Car has_many Passengers
Car has_one Driver, :class => Passenger
I’d do something similar.
Actually if I had the freedom, I’d probably rename the class Passenger
to something like Person since Driver and Passenger are really roles,
not entities.
class Person < ActiveRecord::Base
belongs_to :car
end
class Car < ActiveRecord::Base
belongs_to :driver, :class => ;person
has_many :passengers, :class => person
end
–
Rick DeNatale
Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale