【问题标题】:Rails 5 - return records with an association count > 0 - PSQL/ActiveRecordRails 5 - 返回关联计数 > 0 的记录 - PSQL/ActiveRecord
【发布时间】:2016-09-28 11:20:59
【问题描述】:

我有 2 个模型;类别和产品,我想返回至少分配有 1 个产品的所有类别的列表。

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

Products 也通过连接表设置关联,并且产品类别设置为产品和类别的 belongs_to。

我只是想创建一个助手来列出类别,并且只想返回有产品的那些。

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

【问题讨论】:

  • Category.joins(:product_categories) 应该为您提供所有类别的列表,其中至少包含 1 个product_category

标签: ruby-on-rails postgresql activerecord psql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2010-10-06
    • 2012-03-01
    • 1970-01-01
    相关资源
    最近更新 更多