Malek Zalfana
Malek Zalfana

Reputation: 318

How to delete user's post after he deleted his account? - Rails

I'm guessing something should be added to the post model. After I cancel my account I still find the posts but with nil user. How can I remove user's post with the account?

Upvotes: 0

Views: 979

Answers (3)

debasish117
debasish117

Reputation: 196

You can do something like before your delete action is performed you can find the related posts of user and delete them first. Then after you can delete the user .

Upvotes: 0

Hasmukh Rathod
Hasmukh Rathod

Reputation: 1118

In your User model, you need to modify the below association by adding the dependent option:

has_many :posts, dependent: :destroy

Reference: Rails ActiveRecord::Associations::ClassMethods documentation, “Deleting from associations”

Upvotes: 4

user1875195
user1875195

Reputation: 988

You should be able to do something like this in your User model. It will essentially cascade the delete upon deleting a user.

has_many :posts, :dependent => :destroy

Upvotes: 3

Related Questions