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

Viewed 6185

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.

1 Answers
Related