我正在尝试对我的模型进行一些计算,但生成的 sql 无法正常工作。
我有这个模型:
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...
我究竟做错了什么?有没有更好的方法来做到这一点?非常感谢您!