鉴于以下两种模式:
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::StatementIn有效值: PG::UndefinedTable: ERROR:从-子句条目中丢失表格“文件”
我做错了什么?
我在Rails 6中使用Ruby2.6.5
发布于 2020-04-08 13:21:20
您正在查找的查询是(假设正确地创建了迁移,并且将两个模型关联的表称为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关系,因此scientists表中没有对papers的引用(因此不能执行left_joins(:papers))。这种关系看起来是:

有关更多细节,请查看许多协会。
https://stackoverflow.com/questions/60637757
复制相似问题