Ruby-on-rails PG::UndefinedTable:错误:在使用连接和 where 时缺少表的 FROM 子句条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25099668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:50:37  来源:igfitidea点击:

PG::UndefinedTable: ERROR: missing FROM-clause entry for table when using joins and where

ruby-on-railsruby-on-rails-4psql

提问by Huy

I have two models, Courierand Order.

我有两个模型,CourierOrder.

I have the following query below:

我有以下查询:

active_couriers = Courier.
  available_courier_status.
  where(:service_region_id => @service_region.id).
  includes(:orders)

This query works, however, it pulls in all orders. I want to limit the orders to only orders for the day. So I added the following query where("orders.created_at >= ?", Time.zone.now.beginning_of_day).

此查询有效,但是,它会提取所有订单。我想将订单限制为当天的订单。所以我添加了以下查询where("orders.created_at >= ?", Time.zone.now.beginning_of_day)

active_couriers = Courier.
  available_courier_status.
  where(:service_region_id => @service_region.id).
  includes(:current_orders).
  includes(:orders).
  where("orders.created_at >= ?", Time.zone.now.beginning_of_day)

This give me the error:

这给了我错误:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "orders"

What am I doing incorrectly here?

我在这里做错了什么?

回答by Dane O'Connor

Hmm it looks like you're trying to include current_ordersand include order. Are these the same tables with different conditions? This might be confuse active record. Also, I'm pretty sure it's wise to include the referencesmethod when referencing a joined table. Perhaps, try something like this:

嗯,看起来您正在尝试包含current_orders和包含order. 这些是不同条件的相同表吗?这可能会混淆活动记录。另外,我很确定references在引用连接表时包含该方法是明智的。也许,尝试这样的事情:

active_couriers = Courier.includes(:orders)
  .available_courier_status
  .where(:service_region_id => @service_region.id)
  .where("orders.created_at >= ?", Time.zone.now.beginning_of_day)
  .references(:orders)

回答by mattcongel

You can also use eager_loadto provide the same exact behavior as includes+ referencesdoes. It performs the same Left Outer Join on the table passed as an argument, but in a much cleaner manner.

您还可以使用eager_load来提供与includes+完全相同的行为references。它对作为参数传递的表执行相同的左外连接,但方式更简洁。

Docs here: http://apidock.com/rails/v4.2.7/ActiveRecord/QueryMethods/eager_load

文档在这里:http: //apidock.com/rails/v4.2.7/ActiveRecord/QueryMethods/eager_load

Per this example:

根据这个例子:

active_couriers = Courier.eager_load(:orders)
  .available_courier_status
  .where(:service_region_id => @service_region.id)
  .where("orders.created_at >= ?", Time.zone.now.beginning_of_day)

回答by Kiryl Plyashkevich

Make sure to provide .includes(:service_region)before filtering with where.

确保.includes(:service_region)在过滤前提供where.