【发布时间】: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