Let's say I have a Post
model:
class Post < ActiveRecord::Base
belongs_to :category
end
and a Category
model:
class Category < ActiveRecord::Base
has_many: :posts
end
I can use dependent: :destroy
to have all the posts deleted when a specific category is deleted, but I don't want to remove the posts, I just want to remove the association to that specific category by just setting the category_id
column of those posts to nil
.
Is there a "Rails Way" of doing this out of the box, or do I need to use some callbacks?
use dependent: :nullify
Per the Rails guide:
:nullify causes the foreign key to be set to NULL. Callbacks are not executed.
So you'd have:
class Category < ActiveRecord::Base
has_many: :posts,
dependent: :nullify
end
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