title: Rails sum with group by and include
body: <p>I'm trying to make some calculations over my models, but the generated sql is just not working.</p>
  
  <p>I have this models:</p>
  
  <pre><code>class Order &lt; ActiveRecord::Base
    attr_accessible :order_date
    has_many :order_products, dependent: :destroy
  
  class OrderProduct &lt; ActiveRecord::Base
    attr_accessible :amount
    belongs_to :tariff
    belongs_to :order_product_format
    belongs_to :product
  
  class OrderProductFormat &lt; ActiveRecord::Base
    attr_accessible :amount
  
  class Tariff &lt; ActiveRecord::Base
    attr_accessible :price
  </code></pre>
  
  <p>So I created a function in my Order controller to get the total amount of all the orders as follows</p>
  
  <pre><code>def self.global_total_amount
    OrderProduct.joins(:order_product_format, :tariff).sum '((order_products.amount * order_product_formats.amount ) * tariffs.price)'
  end
  </code></pre>
  
  <p>This works as expected, but now I want to group this total amounts by month of the year, so I'm trying to do something like this</p>
  
  <pre><code>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
  </code></pre>
  
  <p>And I get the following error:</p>
  
  <pre><code>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...
  </code></pre>
  
  <p>What am I doing wrong? Is there a better approach to do this?
  Thank you very much in advance!</p>