【问题标题】:Eager loading of deleted records with paranoia's default scope使用偏执狂的默认范围急切加载已删除的记录
【发布时间】:2012-11-11 21:38:55
【问题描述】:

我正在使用 paranoia gem 来“软删除”记录。现在我需要为关联模型急切加载这些记录,其中一些可能已被删除。 Paranoia 将此default_scope 添加到“偏执狂”模型中:

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

所以实际上,我有这些(简化的)模型:

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

class Order
  belongs_to :product
end

我想要实现的是在访问订单时预先加载产品:

Order.includes(:product)

这(来自How to use unscoped on associated relations in Rails3?)在这里不起作用:

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

我知道我可以创建自定义belongs_to 关系到添加 条件(如Eager loading nested association and scope),但我找不到删除 现有的方法那些,如果可能的话。

问题:如何防止将默认范围应用于预加载查询?

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 eager-loading default-scope


【解决方案1】:

好吧,事实证明解决方法是强制加入“偏执狂”模型,从而绕过default_scope

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

不漂亮,但它有效。如果可能,希望得到更好的答案。

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2014-05-21
      • 2016-08-17
      相关资源
      最近更新 更多