加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 用偏执狂的默认范围急切加载已删除的记录

发布时间:2020-12-17 02:19:28 所属栏目:百科 来源:网络整理
导读:我正在使用 paranoia gem来“软删除”记录.现在我需要为关联的模型急切加载这些记录,其中一些可能已被删除. Paranoia将此default_scope添加到“偏执”模型中: default_scope :conditions = { :deleted_at = nil } 所以实际上,我有这些(简化)模型: class Pr
我正在使用 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),但我找不到删除现有关系的方法,如果可能的话.

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

解决方法

好吧,事实证明解决方法是强制连接“偏执”模型,绕过default_scope:

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

不漂亮,但它的工作原理.如果可能的话,想要更好的答案.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读