[英]Rails `has_many` association
I'm new to learning Rails and I'm a bit confused about associations. 我刚接触Rails,对关联有些困惑。
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
. 比方说,我有一个
Car
它可以属于一个Owner
,一个Renter
或Company
,只能属于其中的一个和Owner
, Renter
或Company
可以有很多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
? Car
表上是否应该有owner_id
, render_id
和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. 提前致谢。
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
cars
表中有两个新字段, possessor_type
和possessor_id
,您可以通过迁移将其添加,也可以添加其他可能拥有汽车的模型,而无需在cars
添加更多列
One of possible ways: make Car
to have foreign keys on Owner
, Renter
, Company
. 可能的方法之一:使
Car
在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 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.