Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 479
hattenn Avatar asked Feb 03 '16 07:02

hattenn


1 Answers

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
like image 174
J Plato Avatar answered Nov 15 '22 04:11

J Plato