Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a belongs_to association to Nil when the associated object is destroyed

Say I have:

class Car < ActiveRecord::Base
  belongs_to :brand
end

class Brand < ActiveRecord::Base
  has_many :cars
end

If I destroy a Brand object, the child Cars still have their car.brand_id attributes set to the destroyed brand.id.

How can I null out the car.brand_id of the child Cars when destroying the parent Brand?

I thought the ActiveRecord relationship would handle this, and prevent orphaned objects.

I don't want to dependent: :destroy the Cars, but just want to have their car.brand_id set to nil.

I don't want to have to write an after_commit for this, I want Rails magic to handle this. Or less ideally a foreign key constraint.

like image 730
koonse Avatar asked Dec 05 '13 19:12

koonse


1 Answers

What about dependent: :nullify on Brand model?

4.3.2.4 :dependent

Controls what happens to the associated objects when their owner is destroyed:

...

:nullify causes the foreign keys to be set to NULL. Callbacks are not executed.

...

http://guides.rubyonrails.org/association_basics.html#has-many-association-reference

like image 136
Bob Avatar answered Oct 25 '22 08:10

Bob