Postgres 查询可在控制台上运行,但将其用作视图中的范围会呈现语法错误

Postgres query works on console but using it as a scope in a view renders syntax errors

我正在使用查询从 Subscription.

中获取最旧 authorized_at 日期的 SubscriptionCart

因为 Subscription has_many SubscriptionCart,我使用与订阅 plan_id 相同的 plan_id 过滤购物车。我也对 SubscriptionSubscriptionCart 状态使用 WHERE 语句。

查询似乎在控制台上运行良好,但当我将其放入订阅范围并尝试在我的视图中使用它时,我得到:

PG::SyntaxError: ERROR:  syntax error at or near "WHERE"
LINE 6: ...ubscriptions.id, subscription_carts.authorized_at WHERE "sub...

这是怎么回事?

查询:

select distinct on (s.id) s.id, sc.authorized_at as cart_authorized_at, s.*
from subscriptions s
join subscription_carts sc on sc.subscription_id = s.id and sc.plan_id = s.plan_id
where sc.status = 'processed'
and s.status IN ('authorized','in_trial', 'paused')
order by s.id, sc.authorized_at

范围:

  scope :with_current_price_version, -> {
    select("
      DISTINCT ON (subscriptions.id) subscriptions.id,
      subscription_carts.authorized_at as version_cart_authorized_at,
      subscriptions.*
    ")
    .joins("
      INNER JOIN subscription_carts
      ON subscription_carts.subscription_id = subscriptions.id                 
      AND subscription_carts.plan_id = subscriptions.plan_id   
      WHERE subscription_carts.status = 'processed'
      AND subscriptions.status IN ('authorized','in_trial', 'paused')
      ORDER BY subscriptions.id, subscription_carts.authorized_at
    ")
  }

编辑:将 WHERE、AND 和 ORDER BY 子句移到 .join 之外解决了这个问题。

更新范围如下:

  scope :with_current_price_version, -> {
    select("DISTINCT ON (subscriptions.id) subscriptions.id,
           subscription_carts.authorized_at as version_cart_authorized_at, subscriptions.*")
      .joins("INNER JOIN subscription_carts on subscription_carts.subscription_id = subscriptions.id
             AND subscription_carts.plan_id = subscriptions.plan_id")
      .where("subscription_carts.status = 'processed'
             AND subscriptions.status IN ('authorized','in_trial', 'paused')")
      .order("subscriptions.id, subscription_carts.authorized_at")
  }
class Subscription < ApplicationRecord
  def self.with_latest_subscription_cart
    s = arel_table
    sc = SubscriptionCart.arel_table.alias('sc')
    select(
      'DISTINCT ON(subscriptions.id)',
      :id, # not sure why you want to select this explicitly 
      s[Arel.star],
      sc[:authorized_at]
    )
    .joins(
      s.join(sc).on(
        sc[:subscription_id].eq(s[:id]).and(
          sc[:plan_id].eq(s[:plan_id])
        )
      ).join_sources
    )
    .where(
      status: 'processed',
      sc: {
        status: ['authorized','in_trial', 'paused']
      }
    )
    .order(:id, sc[:authorized_at])
  end
end

不过,如果您将 subscription_carts.plan_id = subscriptions.plan_id 移动到 WHERE 子句中,这样您就可以只使用 joins(:subscription_carts).