Skip to content

with_deleted unscopes everything when joining through multiple associations #282

Description

@heaven

We have Subscriptions, Products, Prices, and AddOns.

class Payments::Subscription < ApplicationRecord
  has_many :subscription_addons,
    class_name: "Payments::SubscriptionAddon", inverse_of: :subscription, dependent: :destroy

  has_many :addons, class_name: "Payments::Product", through: :subscription_addons, source: :product
end

class Payments::SubscriptionAddon < ApplicationRecord
  belongs_to :price, -> { with_deleted },
    class_name: "Payments::Price", inverse_of: :subscription_addons

  has_one :product, class_name: "Payments::Product", through: :price
end

class Payments::Price < ApplicationRecord
  belongs_to :product, -> { with_deleted },
    class_name: "Payments::Product", inverse_of: :prices
end

When I access @subscription.subscription_addons everything is great and it returns only SubscriptionAddons where deleted_at is null.

But when I need to access @subscription.addons, the response also includes Products joined through already deleted SubscriptionAddons. In other words with_deleted that I apply to belongs_to :product/:price also applies to has_many :subscription_addons even thought it wasn't explicitly declared there. Basically, it unscopes where(::deleted_at) where it shouldn't.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions