ruby-on-rails – 如何通过与Active Record关联找到has_many中缺少相关记录的记录?

我们有“主题 – 关系 – 类别”.

也就是说,主题通过关系有很多类别.

我认为很容易得到一个类别的主题

#Relationship  Model
  Topic_id: integer
  Category_id: integer

  @topics=Topic.joins(:relationships)

但是,并非每个主题都有一个类别.那么我们如何检索没有类别的主题呢?
是否有减号查询

也许它看起来像@ topics = Topic.where(‘id NOT IN(?)’,Relationship.all)
我在activerecord equivalent to SQL ‘minus’找到它但不确定这个解决方案.

解决方法

真的,作为一种关系会更好.认为这样可行:
@topics = Topic.joins('left join relationships on relationships.topic_id = topics.id').where('relationships.category_id is null')

或这个:

@topics = Topic
    .joins('left join relationships on relationships.topic_id = topics.id join categories on categories.id = relationships.category_id')
    .group('topics.id').having('count(categories.id) = 0')

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...