I have two models in my Rails app: Product and CardItem
Product has field price
CardItem has field quantity and belongs to Product.
I want to select total price of all card items depending on product.price * quantity
class CardItem < ActiveRecord::Base
belongs_to :product
scope :total_price, -> {
result = joins(:product).select('SUM(products.price * card_items.quantity) as total_price')
result.empty? ? 0 : result.first.total_price
}
end
This code perfectly works in sqlite, but with postgresql it throws error:
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
help my fix this please
p.s. I use Rails 4.0.0