【问题标题】:Rails has_many assign child ids renders parent invalid because parent must have a childRails has_many assign child ids 使父级无效,因为父级必须有一个子级
【发布时间】:2020-04-08 02:19:57
【问题描述】:

这里是模型关联

class Driver
  has_many :cars

  validates :cars, presence: true
end
class Car
  belongs_to :driver
end

汽车记录已经存在。它不需要有驱动程序

id 为 1 的第一辆车,分配给司机 1

driver1.car_ids = [1]

driver1 现在有车了

现在我们用汽车 1 创建司机 2

driver2.car_ids = [1]

driver1 失效,因为它不再有汽车

处理此问题的最佳方法是什么?

【问题讨论】:

  • 无效是什么意思?您能否提供一系列导致意外回溯或输出的命令?
  • 无效,因为汽车存在验证失败。没有回溯,一切顺利

标签: ruby-on-rails has-many


【解决方案1】:

失败的原因是,在您当前的设置中,一辆车只能有一个司机。由于您将 driver1 分配给汽车,然后将 driver2 分配给汽车,因此 driver2 会覆盖 driver1,从而使 driver2 成为汽车所有者。如果您希望一辆车中有很多司机,您应该将您的设置更改为:

class Car
  has_many :drivers
end

这将允许您为您的汽车分配许多司机(或只分配一名司机,如果这是有意的话)。

【讨论】:

    【解决方案2】:

    您的关联失败,因为您的设置中一个司机可以拥有多辆汽车,而一辆汽车属于一个司机。您需要使用连接表和 has_and_belongs_to_many 关联。

    Ruby on Rails Guides - has_and_belongs_to_many

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      相关资源
      最近更新 更多