繁体   English   中英

在 Rails 中查找缺少关联记录的记录

[英]Find records with missing associated records in Rails

我有一个遗留数据库,其中有两个模型:

class Purchase
  belongs_to :product
end

class Product
  has_many :purchases
end

现在,随着时间的推移,一些products被删除了,即使相关的purchases仍然存在于数据库中。 有没有一种方法可以获得从 Rails 控制台中删除相关products的所有Purchases的列表?

我的purchase表引用了product并且有一列product_id

Purchase.left_outer_joins(:product).where(products: {id: nil})

注意导轨5具有left_outer_joins

因此,基本上,这将导致所有没有相关产品的购买。

为什么删除产品时不取消购买?

class Product
  has_many :purchases, :dependent => :nullify
end

这样,您要做的就是查询product_id为null的购买。 希望这可以帮助!

编辑:如果您现在正在使用此方法,以更新旧记录并使它们一致,则应执行以下操作:

Purchase.where.not(product_id: Product.select(:id).distinct).update_all(product_id: nil)

所以像现在这样应该可以工作

Rails 6.1 添加了missing的 wherechain。 现在您可以使用Purchase.where.missing(:products)实现与 Anand 的答案相同的效果

https://edgeapi.rubyonrails.org/classes/ActiveRecord/QueryMethods/WhereChain.html#method-i-missing

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM