我试图按每个商店内商品数量的顺序排列商店列表。我在所有权的商店和产品中间加入。所以,我的模型看起来像:按商店排序商店数量在轨道中
shop.rb
has_many :ownerships
has_many :products, through: :ownerships
product.rb
has_many :ownerships
has_many :shops, through: :ownerships
ownership.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
可能重复的[Rails 3.按匹配次数排列(多对多)](https://stackoverflow.com/questions/16834399/rails-3-order-by-count-of-matches-many- to-many) – Genzume
以上是给我相同的PG :: GroupingError。使用'Shop.all.sort_by {| s | s.products.count}“确实有效,但速度很慢。 – albaba
算什么?独特产品的数量或所有产品的总库存数量,甚至特定产品的数量? – max