【问题标题】:View all records which exist in associated record查看关联记录中存在的所有记录
【发布时间】: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


    【解决方案1】:

    您只需要加入即可。试试

    Category.joins(:listings)
    

    通过这种方式,您应该只看到列表中匹配的行

    【讨论】:

    • 如果您有兴趣编写良好的活动记录查询,我建议您学习一点 SQL
    • 我怎样才能让它只出现一个类别的副本?例如,如果 2 个列表使用相同的类别,它会出现两次
    • 看起来.distinct 可以完成这项工作。这是你的最佳方式吗?
    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2011-07-16
    相关资源
    最近更新 更多