Home > other >  【Rails】acts_as_paranoid environment, I want to physically delete records that use the relation depen
【Rails】acts_as_paranoid environment, I want to physically delete records that use the relation depen

Time:10-15

detail

user.rb

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

post.rb

class Post < ApplicationRecord
  acts_as_paranoid
  belongs_to :user

users_controller.rb

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

When a user is deleted, how should I describe that the user is logically deleted and the post related to the deleted user is physically deleted?
I would like to ask for your wisdom.

environment

rails 6.0

CodePudding user response:

How about doing it in the after_destroy callback?

Looking at the docs I don't see a paranoid equivalent of destroy_all! so you're going to have to do a loop and fall destroy_fully! (which is what paranoia does so this will be no slower src)

class User < ApplicationRecord
  acts_as_paranoid
  has_many :posts
  after_destroy :delete_deps

  def delete_deps
    self.posts.each do |post|
      post.destroy_fully!
    end
  end
end
  • Related