ruby-on-railsrubyruby-on-rails-3has-manyhas-one

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.


Solution

  • 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