Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add with_deleted: true for has_many relationships #290

Open
fmichaut-diff opened this issue Oct 12, 2022 · 1 comment
Open

Add with_deleted: true for has_many relationships #290

fmichaut-diff opened this issue Oct 12, 2022 · 1 comment

Comments

@fmichaut-diff
Copy link

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
Copy link

pilgunboris commented Oct 12, 2022

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants