Rails - 仅查找存在has_many关联记录的记录

Han*_*les 9 postgresql activerecord ruby-on-rails ruby-on-rails-3

我有一个has_many与另一个模型有关系的模型,如下所示:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end
Run Code Online (Sandbox Code Playgroud)

由于有些父母可能没有孩子,我想做一个只返回有孩子的父母的查询.我怎么会这样做?

由于我在Rails 3上执行此操作,如果此查询不使用where.not.语法将会有所帮助.

Aza*_*ine 14

Rails 4

Parent.includes(:child).where.not(children: {id: nil})

要么

Parent.joins(:child).where.not(children: {id: nil}).distinct

Rails 3

Parent.joins(:child).where('children.id NOT NULL').distinct

  • 您应该添加关键字 **references** 以将 **where** 与 **includes** 一起使用,如下所示:`Parent.includes(:children).references(:children).where.not(children: {id:零})` (2认同)

Mar*_*n13 12

关联 (Rails 7+)

Rails 7 引入了一种检查关联是否存在的新方法 - where.linked

请看一下下面的代码片段:

# Before:
account.users.joins(:contact).where.not(contact_id: nil)

# After:
account.users.where.associated(:contact)
Run Code Online (Sandbox Code Playgroud)

这是在后台使用的 SQL 查询的示例:

Post.where.associated(:author)
# SELECT "posts".* FROM "posts"
# INNER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# WHERE "authors"."id" IS NOT NULL
Run Code Online (Sandbox Code Playgroud)

因此,您的具体情况可以重写如下:

Parent.where.associated(:child)
Run Code Online (Sandbox Code Playgroud)

谢谢。

资料来源:

笔记: