2017-10-10 104 views
0

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

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 
+3

可能重複的[Rails 3.按匹配次數排列(多對多)](https://stackoverflow.com/questions/16834399/rails-3-order-by-count-of-matches-many- to-many) – Genzume

+0

以上是給我相同的PG :: GroupingError。使用'Shop.all.sort_by {| s | s.products.count}「確實有效,但速度很慢。 – albaba

+0

算什麼?獨特產品的數量或所有產品的總庫存數量,甚至特定產品的數量? – max

回答

0

我已經嘗試過在我的網站,我認爲我們這個問題只是因爲PG集團請試試這個:

Shop.all.joins(:products).select('products.*').where.not(products: {id: nil}).references(:products).group('products.id') 
+0

這是如此接近,但是,這似乎是訂購的產品,而不是實例,這很奇怪,因爲它返回像'# albaba

0

如果有人遇到同樣的事情,可以將其解決。

所有的答案/評論是超近,但爲了獲得排序由哪些有大部分產品按照從大到小的順序存儲,我使用:

@stores = Store.joins(:products).group('stores.id').order('count(products.id) desc') 

在試圖找到該商店有一個特定品牌的大部分產品按降序排列,我修改了上面的使用方法:

@stores = Store.joins(:products).group('stores.id').where(:products => { :brand_id => @brand.id }).order('count(products.brand_id) desc') 

ActiveRecord FTW。