删除has_one id与has_many主键关联?

问题描述 投票:0回答:2

我有2个型号:

class Agency < ApplicationRecord
  has_one :branding
end

class Branding < ApplicationRecord
  has_many :agencies
end

当我摧毁任何品牌时,它仍然保持与原子能机构的关键,在那里我做了一个领域branding_id

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

ruby-on-rails ruby ruby-on-rails-3 has-many has-one
2个回答
1
投票

首先,如果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

1
投票

Rails提供此选项,请在下面查看,它会在代理商中将id更新为null。有关更多信息,请查看this

class Branding < ApplicationRecord
  has_many :agencies, dependent: :nullify
end
© www.soinside.com 2019 - 2024. All rights reserved.