简体   繁体   English

查看关联记录中存在的所有记录

[英]View all records which exist in associated record

Goal: I want to show all Category that are currently in existence in the Listing model. 目标:我想显示清单模型中当前存在的所有类别。

For instance, a Listing can have many categories. 例如,清单可以具有许多类别。 Say I have 100 categories and 10 listings but only 20 of those categories are currently being used in the Listing.category_ids, I only want those to appear. 假设我有100个类别和10个列表,但是Listing.category_ids中目前仅使用其中20个类别,我只希望它们出现。

I have tried: 我努力了:

@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}])

And some other similar ways. 和其他一些类似的方式。 BTW, i use Postgres. 顺便说一句,我使用Postgres。

Both of these attempts have only appeared the first category within the Category model, even though that category isn't being used. 即使未使用该类别,这两种尝试都仅出现在Category模型中的第一个类别。

Models: 楷模:

Listing 清单

has_and_belongs_to_many :categories

Categories: 分类:

has_and_belongs_to_many :listings

I then have a Categories_Listings join table too t for it all. 然后我也有一个Categories_Listings连接表。 That is where the associations are stored. 这就是关联的存储位置。

You just need a join for that. 您只需要为此加入。 Try 尝试

Category.joins(:listings)

In this way you should see just rows which have a match in listings 这样,您应该只看到列表中具有匹配项的行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM