Rails 5 - return 条关联计数 > 0 - PSQL/ActiveRecord 的记录

Rails 5 - return records with an association count > 0 - PSQL/ActiveRecord

我有2个模型;类别和产品,我想 return 列出至少分配了 1 个产品的所有类别。

# app/models/category.rb
has_many :product_categories
has_many :products, through: :product_categories

产品也通过关联设置 table,产品类别设置为 belongs_to 产品和类别。

我只是想创建一个帮助程序来列出类别,并且只想 return 有产品的类别。

def category_list
   # Return categories here with at least 1 product
end

Category上使用counter_cache,重置模型的计数器,然后就可以查询Category.where('product_count > ?', 0)