我試圖按每個商店內商品數量的順序排列商店列表。我在所有權的商店和產品中間加入。所以,我的模型看起來像:按商店排序商店數量在軌道中
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