[英]ActiveRecord, find all records where associated record EITHER does not exist OR exists with nil status
[英]View all records which exist in associated record
目标:我想显示清单模型中当前存在的所有类别。
例如,清单可以具有许多类别。 假设我有100个类别和10个列表,但是Listing.category_ids中目前仅使用其中20个类别,我只希望它们出现。
我努力了:
@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连接表。 这就是关联的存储位置。
您只需要为此加入。 尝试
Category.joins(:listings)
这样,您应该只看到列表中具有匹配项的行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.