ActsAsParanoid / acts_as_paranoid

ActiveRecord plugin allowing you to hide and restore records without actually deleting them.
MIT License
1.45k stars 190 forks source link

Add `with_deleted: true` for has_many relationships #290

Open fmichaut-diff opened 1 year ago

fmichaut-diff commented 1 year ago

Currently, you can create a model with with_deleted: true if you want this model to still show deleted records, but only for belongs_to assotiations.

class Model < ApplicationRecord
  belongs_to :parent_model, with_deleted: true # works
  has_many :childrens, with_deleted: true # Does not work
end

The second exemple currently raises this error

Unknown key: :with_deleted. Valid keys are: :class_name, :anonymous_class, :primary_key, :foreign_key, :dependent, :validate, :inverse_of, :strict_loading, :autosave, :before_add, :after_add, :before_remove, :after_remove, :extend, :counter_cache, :join_table, :index_errors, :ensuring_owner_was, :through, :source, :source_type (ArgumentError)

In some cases, we might want to be able to use with_deleted: true for has_many relationships. Exemple:

class OrderItem < ApplicationRecord
  acts_as_paranoid
end

class Order < ApplicationRecord
  has_many :order_items
end

class SalesReceipt < ApplicationRecord
  belongs_to :order
  has_many :order_items, through: :order, with_deleted: true # This currently does not work
end

In this situation, if I delete an item from an order (let's say the customer did not want it anymore), I might still need the reference inside the sales receipt since the receipt was printed before the item was deleted, so it should still have access to it (because it depends on it).

Is it something that could be implemented ?

pilgunboris commented 1 year ago

@fmichaut-diff try defining your association with { with_deleted } scope like this:

class SalesReceipt < ApplicationRecord
  belongs_to :order
  has_many :order_items, -> { with_deleted }, through: :order
end

Depending on your needs sometimes it might make sense to define 2 associations :order_items and :order_items_with_deleted.