Last Updated: February 25, 2016
·
748
· ktkaushik

Remove method for Mongoid::Paranoia

module Mongoid
 module Paranoia
 extend ActiveSupport::Concern

 module ClassMethods
 end

 module InstanceMethods

 # 'remove' method is soft-delete for Paranoia module which i read somewhere is extracted from
 # 'acts_as_paranoia' gem. In any which way, i was still unable to use the callback before_destroy, hence this hack.
 def remove
 super
 has_deleted_the_record = false
 if self.remove_associated_records
 return has_deleted_the_record = true
 end
 has_deleted_the_record
 end

 # What would this do ?
 # Basically, this would fetch all the associated models with embeds_many and references_many, we do not want parent model. 
 # We only want the child model to delete( or in this case 'remove') the records.
 # basic algo :
 # 1. Get the first element i.e. model_info from the array of the associated models.
 # 2. Check if its nil
 # 3. If not, downcase and pluralize and call that method.
 # for ex: Client.first.projects
 # 4. remove them
 # NOTE: remove is now recursive
 def remove_associated_records
 associated_model = self.class.reflect_on_all_associations(:embeds_many).first || self.class.reflect_on_all_associations(:references_many).first
 deleted = false
 if !associated_model.nil?
 self.send( associated_model.class_name.downcase.pluralize ).each do |record|
 record.remove
 deleted = true
 end 
 else
 return deleted = true 
 end
 return deleted
 end
 end
 end
end