【问题标题】:3 Tables Share an Association table3 个表共享一个关联表
【发布时间】: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


【解决方案1】:

根据我上面的假设,我测试了关联模型,并在关联中选择了汽车/卡车,这很有效:

class Assoc < ApplicationRecord
  belongs_to :part
  belongs_to :car,   optional: true
  belongs_to :truck, optional: true
end

我认为这现在需要一个验证器来检查car_id 或truck_id 的存在。我还没有实现它,但我认为 Assoc 应该包括这样的东西:

class Assoc < ApplicationRecord
  belongs_to :part
  belongs_to :car,   optional: true
  belongs_to :truck, optional: true

  validates :car_id,   presence: true, unless: :truck_id
  validates :truck_id, presence: true, unless: :car_id
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多