2012-11-07 182 views
2

我想對我的模型進行一些計算,但生成的SQL只是不工作。Rails與分組和,包括

我有這個型號:

class Order < ActiveRecord::Base 
    attr_accessible :order_date 
    has_many :order_products, dependent: :destroy 

class OrderProduct < ActiveRecord::Base 
    attr_accessible :amount 
    belongs_to :tariff 
    belongs_to :order_product_format 
    belongs_to :product 

class OrderProductFormat < ActiveRecord::Base 
    attr_accessible :amount 

class Tariff < ActiveRecord::Base 
    attr_accessible :price 

所以我創造了我的訂單控制器的功能,讓所有的訂單總金額如下

def self.global_total_amount 
    OrderProduct.joins(:order_product_format, :tariff).sum '((order_products.amount * order_product_formats.amount) * tariffs.price)' 
end 

可正常工作,但現在我想將這一總金額按一年的月份分組,所以我試圖做這樣的事情

def self.month_total_amount 
    OrderProduct.includes(:order).joins(:order_product_format, :tariff, :order).group('"order"."order_date"').sum('((order_products.amount * order_product_formats.amount) * tariffs.price)') 
end 

而且出現以下錯誤:

SELECT SUM(((order_products.amount * order_product_formats.amount) * tariffs.price)) AS      sum_order_products_amount_all_order_product_formats_amount_all_, "order"."order_date" AS order_order_date FROM "order_products" INNER JOIN "order_product_formats" ON "order_product_formats"."id" = "order_products"."order_product_format_id" INNER JOIN "tariffs" ON "tariffs"."id" = "order_products"."tariff_id" INNER JOIN "orders" ON "orders"."id" = "order_products"."order_id" GROUP BY "order"."order_date" 

ActiveRecord::StatementInvalid: PG::Error: ERROR: missing FROM-clause entry for table "order" 
LINE 1: ...cts_amount_all_order_product_formats_amount_all_, "order"."o... 

我在做什麼錯?有沒有更好的方法來做到這一點? 非常感謝您提前!

回答

1
def self.month_total_amount 
    OrderProduct.includes(:order).joins(:order_product_format, :tariff, :order).group('orders.order_date').sum('((order_products.amount * order_product_formats.amount) * tariffs.price)') 
end 

您似乎已命名您的訂單表錯誤。您不會將表格和字段放在引號中。

所以像這樣= group('orders.order_date')

不喜歡這樣= group('"order"."order_date"')