2

给定以下两个模型:

class Scientist < ApplicationRecord
  has_and_belongs_to_many :papers
end

class Paper < ApplicationRecord
  has_and_belongs_to_many :scientists
end

所以每个科学家都有很多论文,每篇论文都有很多科学家(可以说是作者)。我的目标是找到所有没有与他们相关的论文的科学家。

Scientist.left_joins(:papers).where(papers: {id: nil}).pluck(:name)

这会引发以下错误:

ActiveRecord::StatementInvalid: PG::UndefinedTable: 错误: 缺少表“论文”的 FROM 子句条目

我究竟做错了什么?

我正在使用带有 Rails 6 的 Ruby 2.6.5

4

1 回答 1

1

您正在查找的查询是(假设正确创建了迁移并且调用了与两个模型相关的表scientists_papers):

Scientist.includes(:scientists_papers).where(scientists_papers: {scientist_id: nil})

它生成一个 SQL 查询,如:

SELECT "scientists".* FROM "scientists" LEFT OUTER JOIN "scientists_papers" ON "scientists_papers"."scientists_id" = "scientists"."id" WHERE "scientists_papers"."scientists_id" IS NULL

当您使用关系时,表has_and_belongs_to_many中没有引用(因此您不能这样做)。关系如下:papersscientistsleft_joins(:papers)

在此处输入图像描述

查看有关 has_and_belongs_to_many 关联的 Rails 文档以获取更多详细信息。

于 2020-04-08T13:21:20.197 回答