Anshul Riyal
Anshul Riyal

Reputation: 133

Delete has_one id associate with has_many primary key?

I have 2 models :

class Agency < ApplicationRecord
  has_one :branding
end

class Branding < ApplicationRecord
  has_many :agencies
end

when I was destroying any branding, it still keeps its key with the Agency, where I made a field branding_id.

I want something which nullifies it when any branding got to destroy in the process. It automatically updates the agency branding_id to null.

Upvotes: 0

Views: 55

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51161

First of all, if Agency model has branding_id column, it should have belongs_to instead of has_one and provide optional: true option to make branding association not required:

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

Second, to do this, you should use nullify option, like this:

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

Upvotes: 1

Vishal
Vishal

Reputation: 7361

Rails provides this option, please check below, it will update id to null in agency. for more info check this

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

Upvotes: 2

Related Questions