关系:
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...
有什么可以解决这个问题?
答案 0 :(得分:-6)
从错误中您可以看到您应该尝试在users.id
子句中加入GROUP BY
:
.group('products.id, users.id')