急于加载带有偏执狂默认作用域的已删除记录 [英] Eager loading of deleted records with paranoia's default scope
问题描述
我正在使用偏执狂 gem来软删除"记录.现在,我需要为关联的模型加载这些记录,其中一些记录可能已被删除.偏执狂将此default_scope
添加到偏执狂"模型中:
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)
这(来自如何在Rails3吗?)在这里不起作用:
This (from How to use unscoped on associated relations in Rails3?) does not work here:
Product.unscoped { Order.includes(:product) }
我知道我可以为 add 条件创建自定义的belongs_to
关系(如
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?
推荐答案
好吧,事实证明,解决方法是在偏执"模型上强制加入联接,从而绕过default_scope
:
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.
这篇关于急于加载带有偏执狂默认作用域的已删除记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!