Eager loading of deleted records with paranoia's default scope

我是研究僧i 提交于 2019-12-07 10:58:28

问题


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?


回答1:


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.




回答2:


This bug is fixed in rails >= 4.1.8.

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

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



来源:https://stackoverflow.com/questions/13335726/eager-loading-of-deleted-records-with-paranoias-default-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!