Note that there are some explanatory texts on larger screens.

plurals
  1. POActiveRecord & PostgreSQL ordering error
    text
    copied!<p>I have two models in my Rails app: Product and CardItem</p> <p>Product has field <em>price</em></p> <p>CardItem has field <em>quantity</em> and belongs to Product.</p> <p>I want to select total price of all card items depending on product.price * quantity</p> <pre><code>class CardItem &lt; ActiveRecord::Base belongs_to :product scope :total_price, -&gt; { result = joins(:product).select('SUM(products.price * card_items.quantity) as total_price') result.empty? ? 0 : result.first.total_price } end </code></pre> <p>This code perfectly works in sqlite, but with postgresql it throws error:</p> <pre><code>PG::GroupingError: ERROR: column "card_items.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...t_id" WHERE "card_items"."user_id" = $1 ORDER BY "card_item... ^ : SELECT SUM(products.price * card_items.quantity) as total_price FROM "card_items" INNER JOIN "products" ON "products"."id" = "card_items"."product_id" WHERE "card_items"."user_id" = $1 ORDER BY "card_items"."id" ASC LIMIT 1 ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "card_items.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...t_id" WHERE "card_items"."user_id" = $1 ORDER BY "card_item... ^ : SELECT SUM(products.price * card_items.quantity) as total_price FROM "card_items" INNER JOIN "products" ON "products"."id" = "card_items"."product_id" WHERE "card_items"."user_id" = $1 ORDER BY "card_items"."id" ASC LIMIT 1 </code></pre> <p>help my fix this please </p> <p>p.s. I use Rails 4.0.0</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload