在 Rails 范围查询中使用多个表

Using multiple tables in Rails scope query

在我的购物车模型中,其中 has_many 个子购物车和 belongs_to 个位置,我正在尝试创建一个范围查询,在其中我获取所有具有 created_at 个子购物车的购物车Cart.Location.active_minutes 的特定时间量之外的时间戳。我在尝试找到一种在查询中使用 location.active_minutes 的方法时遇到问题。我一直收到未定义的 table 错误。

这基本上就是我目前所拥有的。

scope :inactive_cart_bucket, -> {
  where('EXISTS (SELECT s.cart_id FROM cart_subcarts s WHERE (s.cart_id = cart.id) AND (? - s.created_at) / 3600 > cart.location.active_minutes)', Time.zone.now.utc)
}

您必须访问 locations table,或许可以通过购物车模型中的 belongs_to 关系加入它:

scope :inactive_cart_bucket, -> {
  joins(:location).where(
    "EXISTS (
      SELECT s.cart_id
      FROM cart_subcarts s
      WHERE (s.cart_id = cart.id)
      AND ((? - s.created_at) / 3600) > locations.active_minutes
    )",
    Time.zone.now.utc
  )
}

请注意,这是一个 INNER JOIN,根据您要执行的操作,您可能需要一个不同的。