我的产品模型中有这个方法可以满足我的需要:
def self.available
available = []
Product.all.each do |product|
if product.quantity > product.sales.sum(:quantity)
available << product
end
end
return available
end
但是,我想知道是否有更有效的方法来做到这一点,也许只需要调用一次数据库。
最佳答案
你可以试试:
Product.where("products.quantity > Coalesce((select sum(s.quantity) from sales s where s.product_id = products.id), 0)")
关于sql - 对多个父记录的子项属性进行 SUM 运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032322/