【发布时间】:2017-10-11 14:09:54
【问题描述】:
我正在尝试根据每个商店中的产品数量来订购商店列表。我在 Shop 和 Product 之间有一个连接,即所有权。所以我的模型看起来像:
shop.rb
has_many :ownerships
has_many :products, through: :ownerships
产品.rb
has_many :ownerships
has_many :shops, through: :ownerships
所有权.rb
belongs_to :product
belongs_to :shop
我将如何转换此查询以按数量订购产品?
@shops = Shop.all.includes(:products).where('products.id IS NOT NULL').references(:products).order(id :desc)
我尝试过.group('id').order('count(*) DESC') 的变体,例如:
@shops = Shop.all.includes(:products).where('products.id IS NOT NULL').references(:products).group(:id).order('count(*) DESC')
但似乎无法绕过像
这样的错误ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "products.id" must appear in the GROUP BY clause or be used in an aggregate function
【问题讨论】:
-
上面给了我同样的 PG::GroupingError。使用
Shop.all.sort_by { |s| s.products.count }确实有效,但速度很慢。 -
算什么?唯一产品的数量或所有产品的总库存数量,甚至是特定产品的数量?
-
商店按唯一产品总数(降序)分组。
标签: ruby-on-rails postgresql activerecord