Eager loading of deleted records with paranoia's default scope
Asked Answered
H

2

5

I'm using the paranoia gem to "soft-delete" records. Now I need to eager load these records, some of which might have been deleted, for an associated model. Paranoia adds this default_scope to the "paranoid" model:

default_scope :conditions => { :deleted_at => nil }

So in effect, I have these (simplified) models:

class Product
  has_many :orders
  default_scope :conditions => { :deleted_at => nil }
end

class Order
  belongs_to :product
end

What I'm trying to achieve is to eager-load the products when accessing orders:

Order.includes(:product)

This (from How to use unscoped on associated relations in Rails3?) does not work here:

Product.unscoped { Order.includes(:product) }

I know I could create a custom belongs_to relationship to add conditions (as in Eager loading nested association and scope), but I can't find a way to remove existing ones, if that's even possible.

Question: How do I prevent the default scope from being applied to the eager loading query?

Headwaters answered 11/11, 2012 at 21:38 Comment(1)
Just found this related question, which is still unanswered: #3963624Headwaters
H
3

Well, it turns out the workaround is to force a join on the "paranoid" model, which circumvents the default_scope:

Order.joins(:product).includes(:product)

Not pretty, but it works. Would like a better answer if possible.

Headwaters answered 11/11, 2012 at 22:2 Comment(0)
A
2

This bug is fixed in rails >= 4.1.8.

https://github.com/rails/rails/issues/11036

https://github.com/rails/rails/pull/17360

Adelbert answered 23/7, 2015 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.