Manvendra singh
Manvendra singh

Reputation: 41

dependent: :destroy doesn't work on has_one relation

If I delete child record so parent record does not get deleted automatically.

class User < ActiveRecord::Base
    has_one :agency, dependent: :destroy
    accepts_nested_attributes_for :agency 
end

class Agency < ActiveRecord::Base
    belongs_to :user
    accepts_nested_attributes_for :user
end

if @agency.present?
   @agency.user.destroy
   flash[:notice] = 'Agency Deleted'                  
end

Destroy child record so parent record automatically destroy.

Upvotes: 2

Views: 1000

Answers (2)

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

I think, your models could be re-written like this to achieve expected output.

class User < ActiveRecord::Base
    has_one :agency # Change
    accepts_nested_attributes_for :agency 
end

class Agency < ActiveRecord::Base
    belongs_to :user, dependent: :destroy # Change
    accepts_nested_attributes_for :user
end

if @agency.present?
   @agency.destroy # Change
   flash[:notice] = 'Agency Deleted'                  
end

Let's think logically now.

What have you changed is, you made User dependent on Agency and now it's rails doable to form a parent-child relationship to get accepted output. So when you destroy an @agency, it will also delete the dependent user record.

Upvotes: 1

NN796
NN796

Reputation: 1267

You should use the following code to delete a user and its associated agency without making any change to your model.

class User < ActiveRecord::Base
    has_one :agency, dependent: :destroy
    accepts_nested_attributes_for :agency 
end

class Agency < ActiveRecord::Base
    belongs_to :user
    accepts_nested_attributes_for :user
end

if @agency.present?
   user = @agency.user #Change
   user.destroy # This will destroy both user and associated agency.
   flash[:notice] = 'Agency and User Deleted'                  
end

A complete official guide on dependent: :destroy can be find here.

Upvotes: 0

Related Questions