Delete a user together with his posts

Viewed 87

I have two models - User and Post. User has_many :posts and Post belongs_to :user. I want to delete user's posts automatically when the user is deleted. How can I do this? I am very new to ruby..

class User < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :user
end

class UsersController < ApplicationController
  def destroy
    @user = User.find_by(id:params[:id])
    @user.posts
    @user.destroy
  end
end

I've tried the code above, but still only the user is deleted, not his posts. Thanks in advance!

1 Answers

You need dependent option for has_many:

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
end

With it you delete only a needed user, his posts are destroyed automagically

def destroy
  @user = User.find_by(id: params[:id])
  @user.destroy
end

Please, read more about it in guides

Related