Rails查询:根据最新的子记录获取所有父记录

ant*_*tin 2 activerecord ruby-on-rails

订单has_manyorder_events。

Anorder_event是订单状态的记录,例如pending_approvalconfirmed等。

通过创建 来跟踪订单的更改order_events

我通常通过执行以下操作来获取订单的当前状态:order.order_events.last.try(:state)

我想要一个查询来获取具有给定当前状态的所有订单,例如当前状态为 的所有订单cancelable

我最初在模型中有一个范围OrderEvent

scope :cancelable, -> { where('state = ? OR state = ?', 'pending_approval', 'pending_confirmation') }
Run Code Online (Sandbox Code Playgroud)

然后是模型中的范围Order

scope :with_dates_and_current_state_cancelable, -> { with_dates.joins(:order_events).merge(OrderEvent.cancelable) }
Run Code Online (Sandbox Code Playgroud)

并只是将后者用于其他目的。

这里的问题是它返回当前或过去满足条件的所有订单。

获取当前满足条件的所有订单的最佳方式是什么?

ant*_*tin 5

我最终使用了这样的查询:

scope :with_dates_and_current_state_cancelable, -> {
  with_dates
  .joins(:order_events)
  .where('order_events.created_at = (SELECT MAX(order_events.created_at) FROM order_events WHERE order_events.order_id = orders.id)')
  .where('order_events.state = ? OR order_events.state = ?', 'pending_approval', 'pending_confirmation')
  .group('orders.id')
}
Run Code Online (Sandbox Code Playgroud)

读起来有点困难,但似乎有效。