ruby-on-railsrubynested-formsruby-paranoia

Soft-deleted object from parent model not accessible in my child model


My user is allowed do delete some of the resources he has created himself but when he is destroying a resource, there is is problem because I have a model that called resourcequantity that depend on the resource model and I don't want to create a dependent destroy as it will impact the workgroups my user has already created (workgroup is a model containing multiple resources through resource_quantities see below).

What I am trying to do is allowing my user to softly delete its resources while keeping the resource in the database to keep all documents unchanged even if some resources have been destroyed.

I am currently using the paranoia gem and I have tried to implement dependent: :nullify without big success. When using paranoia gem I got an NoMethodError for nill class as it will only look for the resources where deleted_at is null.

I am a bit lost and don't really where to begin.

Here are my three models

class Resource < ApplicationRecord
acts_as_paranoid

  has_many :workgroups, through: :resource_quantities
  has_many :resource_quantities, inverse_of: :resource, dependent: :nullify
  accepts_nested_attributes_for :resource_quantities, allow_destroy: true
end

class ResourceQuantity < ApplicationRecord

  belongs_to :workgroup, optional: true, inverse_of: :resource_quantities
  belongs_to :resource, optional: true, inverse_of: :resource_quantities
  accepts_nested_attributes_for :resource, :allow_destroy => true

  validates :workgroup, uniqueness: { scope: :resource }
end

 class Workgroup < ApplicationRecord
     acts_as_paranoid

   has_many :resource_quantities, inverse_of: :workgroup, dependent: :destroy
   has_many :resources,  through: :resource_quantities, dependent: :nullify


   accepts_nested_attributes_for :resource_quantities, allow_destroy: true
   belongs_to :contractor

   belongs_to :workgroup_library, optional: true
   validates :name, presence: true
 end

Is it possible to do something like this where the resource would be softely deleted ?

def total_cost_price
     total_cost_price = 0
     self.resource_quantities.each do |f|
       total_cost_price += f.resource.purchase_price
     end
     total_cost_price.round(2)
  end

I am not the best in ruby so if you have any advices please feel free to share. Thank you in advance


Solution

  • Ok this issue has been resolved by defining resource as such in the models that was belonging to the Resource model.

      def resource
        Resource.unscoped {super}
      end
    

    thanks to paranoia I can access my resources from my other models even if they have been deleted from the the Resource model. (No need to nullified the relationship)

    Resource.unscoped {super}
    

    it actually removes the "WHERE ("resources"."deleted_at" NULL)" you can observed in your consol which is pretty handy.