删除与 has_many 主键关联的 has_one id?

Delete has_one id associate with has_many primary key?

我有 2 个模型:

class Agency < ApplicationRecord
  has_one :branding
end

class Branding < ApplicationRecord
  has_many :agencies
end

当我销毁任何品牌时,它仍然保留着它在代理处的密钥,我在那里创建了一个字段branding_id

我想要一些东西,当任何品牌在此过程中被破坏时,它就会使它无效。 它会自动将代理商 branding_id 更新为 null

Rails提供了这个选项,请看下面,它会更新代理中的id为null。有关更多信息,请查看 this

class Branding < ApplicationRecord
  has_many :agencies, dependent: :nullify
end

首先,如果 Agency 模型有 branding_id 列,它应该有 belongs_to 而不是 has_one 并提供 optional: true 选项来制作 branding 不需要关联:

class Agency < ApplicationRecord
  belongs_to :branding, optional: true
end

其次,为此,您应该使用 nullify 选项,如下所示:

class Branding < ApplicationRecord
  has_many :agencies, dependent: :nullify
end