7

关系:

Item belongs to Product
Product belongs to User

商品型号范围:

  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')
  }

以上结果产生以下 SQL 语句:

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

这里的问题是发生错误:

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...

有什么办法可以解决这个问题?

4

1 回答 1

-6

从错误中您可以看到您应该尝试users.idGROUP BY子句中包含:

 .group('products.id, users.id')
于 2013-04-30T09:59:57.350 回答