2017-10-10 84 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。