Tim Yip
Tim Yip

Reputation: 123

Rails: How to destroy all user's posts when user is destroyed

Currently I have a SuperAdmin who can destroy users and posts.

However, there's a problem when destroying users. Since all the user's old post still exist, there's a bunch of posts left with blank users. Errors ensue.

Would you know how to code it so that when the user is destroyed, all posts of that user are also destroyed? Here is what I'm using in the SuperAdmin controller.

class SuperAdminController < ApplicationController
  layout 'super_admin'
  before_action :authenticate_super_admin!
end  


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

    if @user.destroy
        redirect_to :back, notice: "User deleted."
    end
  end

Thanks in advance and for your patience. I am new to coding.

Upvotes: 1

Views: 678

Answers (1)

Kirka121
Kirka121

Reputation: 505

use the dependent option on the association.

here is an example of a model definition. when you delete a post, its assets will be deleted as well, as part of the dependent association:

class Post < ActiveRecord::Base
  has_many :assets, dependent: :destroy
end

source: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Upvotes: 7

Related Questions