Reputation:
I'm new to learning Rails and I'm a bit confused about associations.
Say for example, I have a Car
which can belong to either a Owner
, a Renter
or a Company
and can only belong to one of them and a Owner
, Renter
or Company
can have many Cars
.
How would you recommend I go about modelling this scenario? Should there be three foreign keys on the Car
table for owner_id
, render_id
and company_id
? Or have some sort of join table for each of them which would result in something like:
| car_id | owner_id | |--------|----------| | 1 | 1 | | 2 | 1 | | 3 | 1 |
Or is there another way to achieve this? While considering that more dependents (more groups of renters, owners etc.) could be added.
Thanks in advance.
Upvotes: 0
Views: 74
Reputation: 36860
This is a classic example of where you would use a polymorphic association.
class Car
belongs_to :possessor, polymorphic: true
end
class Owner
has_many :cars, as: :possessor
end
class Renter
has_many :cars, as: :possessor
end
class Company
has_many :cars, as: :possessor
end
There are two new fields in the cars
table, possessor_type
and possessor_id
and you can add them with a migration, and you can add other models that might possess a car and there's no need to add more columns to cars
Upvotes: 3
Reputation: 2384
One of possible ways: make Car
to have foreign keys on Owner
, Renter
, Company
.
Here is an example.
class Car < ApplicationRecord
belongs_to :owner
belongs_to :renter
belongs_to :company
end
class Owner < ApplicationRecord
has_many :cars
end
class Renter < ApplicationRecord
has_many :cars
end
class Company < ApplicationRecord
has_many :cars
end
Cars table id| owner_id | renter_id | company_id | - |----------|-----------|------------| 1 | 1 | 1 |2 | 2 | 1 | 1 |1 | 3 | 3 | 2 |1 |
Upvotes: 0