获取子项总和(数量)小于父项(也是数量)的所有记录

agu*_*taf 2 ruby activerecord ruby-on-rails

我试图获得所有产品销售数量总和少于产品数量的产品.

这是我试过的:

class Product < ActiveRecord::Base
  has_many :sales

  scope :available, lambda { where(sales.sum(:quantity) < quantity)}
end
Run Code Online (Sandbox Code Playgroud)

但这给了我undefined local variable or method `sales' for #<Class:0x007fd2f571ac58> 如何解决这个问题?

cha*_*sto 5

sum您的表中的特定字段是由分组你需要的行中的SQL语句,然后应用聚合函数就可以得到.

您的具体问题可能同样在ActiveRecord中翻译:

Product.joins(:sales).
        group("sales.product_id").
        having("sum(sales.quantity) < sum(products.quantity)").
        select("products.*")
Run Code Online (Sandbox Code Playgroud)

您必须使用having在这里,因为where没有对聚合函数应用(又名sum,count,avg等)