【发布时间】:2022-01-09 06:52:27
【问题描述】:
我有两个独立的模型,我想通过相同的关联链接到第三个共享模型。我可以有两个独立的关联表,但想共享以简化 SQL 报告。 这个例子是为了简化现实而假设的;不要打它。
class Assoc < ApplicationRecord
belongs_to :part
belongs_to :car
belongs_to :truck
end
class Part < ApplicationRecord
has_many :assocs
has_many :cars, through: :assocs
has_many :trucks, through: :assocs
end
class Car < ApplicationRecord
has_many :assocs
has_many :parts, through: :assocs
end
class Truck < ApplicationRecord
has_many :assocs
has_many :parts, through: :assocs
end
目前在保存 Truck 或 Car 时会失败。我不确定为什么正如car.errors 没有透露任何内容。猜测该关联可能需要存在 3 个 ID,而我只希望它具有 Part 和 Car 或 卡车,但不是全部三个。上述模型转换为具有以下架构的 SQL 表:
协会
| column | type | example data |
|---|---|---|
| id | bigint | 1,2,3,... |
| part_id | bigint | 1,2,3,... |
| car_id | bigint | 1,2,3,... |
| truck_id | bigint | 1,2,3,... |
我认为理想情况下,我更喜欢具有数据库类/子类引用的表。不用多想,像下面这样,虽然它可能需要自己的问题。
| column | type | example data |
|---|---|---|
| id | bigint | 1,2,3,... |
| vehicle_id | bigint | 1,2,3,... |
| vehicle_type | text | Car or Truck; the field could also be called table_name with cars or trucks being the value |
【问题讨论】:
-
令我惊讶的是,我所追求的正是多态关联的作用(掌心),我从来没有设置或使用过。 这很容易。
标签: ruby-on-rails activerecord ruby-on-rails-5