Rails 5 LEFT OUTER JOIN包含条件之外的记录

时间:2019-01-03 06:41:53

标签: ruby-on-rails ruby-on-rails-5 left-join

这让我发疯,我想要另外一双眼睛。我有以下型号:

class Client
  has_many: client_orders
end

class ClientOrders
  belongs_to :client
end

现在,我正在尝试仅获取过去30天内创建的客户的订单。所以我这样写:

time_range = (30.days.ago - 1.day)..Time.now.midnight
@clients = Client.left_outer_joins(:client_orders).where( client_orders: { created_at: time_range } )

我认为逻辑是正确的。现在,发生以下情况:

我写:@clients.first.client_orders.first

第一个记录是:

=> #<ClientOrder:0x00007f364764b3b8
 id: 1,
 client_order_number: "25970",
 status: "pending",
 client_id: 3,
 client_user_id: 8,
 shipping_cost_cents: 287,
 shipping_cost_currency: "USD",
 taxes_cents: 8800,
 taxes_currency: "USD",
 created_at: Fri, 16 Feb 2018 00:00:00 UTC +00:00,
 updated_at: Mon, 31 Dec 2018 21:51:54 UTC +00:00,
 subtotal_cents: 3426500,
 subtotal_currency: "USD",
 quickbooks_id: nil,
 sync_token: nil,
 convenience_fee_cents: 0,
 convenience_fee_currency: "USD">

是否注意到created_at日期?现在,真正有趣的是,如果我这样做:

@clients.first.client_orders.first.created_at === time_range
D, [2019-01-03T06:28:53.885281 #1] DEBUG -- :   CACHE ClientOrder Load (0.0ms)  SELECT  "client_orders".* FROM "client_orders" WHERE "client_orders"."client_id" = $1 ORDER BY "client_orders"."id" ASC LIMIT $2  [["client_id", 3], ["LIMIT", 1]]
D, [2019-01-03T06:28:53.886633 #1] DEBUG -- :   ↳ (pry):7
=> false

那到底是什么? erb中是否有某些功能很时髦,因此其中包括实际运行时不应该存在的记录或其他内容?我尝试使用其他变量来存储查询,以防其中包含来自先前查询的数据或其他内容,但这没有什么不同。

所以,是的,我的目标是只包含过去30天的订单价值的对象。

奖励积分:获取过去30天内没有订单的客户。我不太确定如何实现目标。我在想这样的事情:@clients = Client.where('id NOT IN (SELECT DISTINCT(client_id) FROM client_orders)')

1 个答案:

答案 0 :(得分:2)

enter image description here我认为您应该声明这样的内容

time_range = (Time.now.midnight - 30.days)..Time.now.midnight
@clients = Client.left_outer_joins(:client_orders).where( client_orders: { created_at: time_range } )