【问题标题】:Ruby on Rails, missing FROM-clause entry for table "pages"Ruby on Rails,缺少表“页面”的 FROM 子句条目
【发布时间】:2017-09-08 17:47:17
【问题描述】:

在将 Rails 应用程序从 3.0 转换为 4.29 后尝试解决这个讨厌的错误

我有一个附加到模型 PostType 的 Scope,它抱怨它需要访问模型页面,这是原始代码:

class PostType < ActiveRecord::Base

  scope :by_domain, lambda { 
    |domain| includes([:pages]).where("pages.domain LIKE ?", domain) 
  }

它抛出了这个错误信息:

  PostType Load (1.2ms)  SELECT "post_types".* FROM "post_types" WHERE (pages.domain LIKE 'test.com')
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "pages"
LINE 1: SELECT "post_types".* FROM "post_types" WHERE (pages.domain ...
                                                       ^
: SELECT "post_types".* FROM "post_types" WHERE (pages.domain LIKE 'test.com')

现在我可以用老式 SQL 解决它:

SELECT "post_types".* FROM "post_types", "pages" WHERE (pages.domain LIKE 'test.com')

哪个有效,但我不知道如何将它翻译成 Rails,有点生疏。

有什么想法吗?

【问题讨论】:

    标签: sql ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    您查询post_types 的方式需要显式引用pages 表。省略references 不会导致JOIN 导致错误的pages 表。

      scope :by_domain, lambda { 
        |domain| includes([:pages]).where("pages.domain LIKE ?", domain).references(:pages) 
      }
    

    这基本上告诉 Rails ORM 查询字符串引用了pages 表,所以它会添加一个连接。

    看看API documentation

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      相关资源
      最近更新 更多