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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With