hattenn
hattenn

Reputation: 4399

Remove the reference id from the record when the owner is deleted

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?

Upvotes: 5

Views: 2036

Answers (1)

J Plato
J Plato

Reputation: 898

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

Upvotes: 9

Related Questions