【问题标题】:Active Record find missing many to manyActive Record 发现多对多缺失
【发布时间】:2020-03-11 13:57:15
【问题描述】:

鉴于以下两个模型:

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: ERROR: missing 表“论文”的 FROM 子句条目

我做错了什么?

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

【问题讨论】:

  • 我认为错误出在其他地方。上面的例子应该运行良好。
  • 用完整的回溯错误更新您的问题?你确定你运行了所有迁移吗?发布 schema.rb ?
  • @ndnenkov 所有涉及的表都有一个 table_prefix (my_app)。连接表称为my_app_scientists_papers。会不会是这个问题?
  • @Severin 我想可能是这样。 where 语句需要表名
  • @Int'lManOfCodingMystery 您如何为上述查询提供连接表的名称?

标签: sql ruby-on-rails postgresql activerecord ruby-on-rails-6


【解决方案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 关系时,scientists 表中没有对papers 的引用(因此您不能使用left_joins(:papers))。关系如下:

查看Rails documentation about the has_and_belongs_to_many Association了解更多详情。

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多