The column "users.id" should appear in the GROUP BY clause or be used in an aggregate function

Relationship:

Item belongs to Product Product belongs to User 

Model Model Volume:

  scope :search, ->(search_term) { select('products.name, users.*, products.brand, COUNT(products.id)') .joins(:product => :user) .where('users.name = ? OR products.brand = ?', search_term, search_term) .group('products.id') } 

The above results are given in the following SQL statement:

 SELECT products.name, users.*, products.brand, COUNT(products.id) FROM "items" INNER JOIN "products" ON "products"."id" = "items"."product_id" INNER JOIN "users" ON "users"."id" = "products"."user_id" WHERE (users.name = 'Atsuete Lipstick' OR products.brand = 'Atsuete Lipstick') GROUP BY products.id 

The problem is that an error occurs:

 ActiveRecord::StatementInvalid: PG::Error: ERROR: column "users.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT products.name, users.*, products.brand, COUNT(product... 

What could be the reason for this?

+6
ruby-on-rails activerecord postgresql
source share
1 answer

From the error, you can see that you should try to include users.id in the GROUP BY :

  .group('products.id, users.id') 
-6
source share

All Articles