Rails活动记录查询结果

时间:2013-07-30 15:42:06

标签: ruby-on-rails-3 activerecord

在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

但这给了我同样的确切结果。我究竟做错了什么?如何才能只添加订单栏不为零的商品?

1 个答案:

答案 0 :(得分:0)

使用!= nil找不到非NULL的记录。您需要使用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
相关问题