【发布时间】:2019-04-17 07:50:44
【问题描述】:
目标: 我想显示列表模型中当前存在的所有类别。
例如,一个列表可以有许多类别。假设我有 100 个类别和 10 个列表,但目前只有 20 个类别在 Listing.category_ids 中使用,我只希望那些出现。
我试过了:
@categories = Category.all.where(id: @listings.each {|listing| listing.category_ids})
@categories = Category.where(id: Listing.all.includes(:category_ids)).order(name: :asc)
@categories = Category.where(id: [@listings.each {|listing| listing.category_ids}])
还有其他一些类似的方式。顺便说一句,我使用 Postgres。
这两种尝试都只出现在 Category 模型中的第一个类别,即使该类别没有被使用。
型号:
上市
has_and_belongs_to_many :categories
分类:
has_and_belongs_to_many :listings
然后我有一个 Categories_Listings 连接表也不能满足所有需求。那是存储关联的地方。
【问题讨论】:
标签: ruby-on-rails ruby