在Rails 3教程之后,我定义了一个范围来限制orders列,并使用一个助手方法对结果求和
class LineItem < ActiveRecord::Base
attr_accessible :cart_id, :product_id, :cart, :product, :quantity
belongs_to :order
belongs_to :product
belongs_to :cart
scope :order, -> {where("order != nil")}
end
帮手
module StoreHelper
def total_product_sold (product)
product.line_items.total_product.sum("quantity")
end
问题是,当我从我的视图中调用total_product_sold时,它会将订单列中的所有数据求和,而不是仅将订单号为!= nil的那些求和。
我也尝试定义一个类方法而不是范围
def self.total_product
where(order !=nil)
end
但这给了我完全相同的结果。我究竟做错了什么?如何获取仅添加订单列不为零的商品的信息?
您无法使用来查找非NULL的记录!= nil
。您需要使用SQL语法IS NOT NULL
:
scope :order, -> { where("line_items.order_id IS NOT NULL") }
或者:
def self.total_product
where("line_items.order_id IS NOT NULL")
end
或者,您可以加入:order
有效地为您进行过滤的关联。但是,这会导致性能下降:
def total_product_sold (product)
product.line_items.joins(:order).sum("quantity")
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句