订单has_many
order_events。
order_event
是订单状态的记录,例如 pending_approval
、confirmed
等。
通过创建 order_events
来跟踪订单更改。
我通常通过执行以下操作来获取订单的当前状态:order.order_events.last.try(:state)
。
我想要一个查询来获取具有给定当前状态的所有订单,例如当前状态为可取消
的所有订单。
我最初在 OrderEvent
模型中有一个范围:
scope :cancelable, -> { where('state = ? OR state = ?', 'pending_approval', 'pending_confirmation') }
然后是 Order
模型中的范围:
scope :with_dates_and_current_state_cancelable, -> { with_dates.joins(:order_events).merge(OrderEvent.cancelable) }
并且只是将后者用于其他目的。
这里的问题是它返回当前或过去满足条件的所有订单。
获取当前满足条件的所有订单的最佳方式是什么?
最佳答案
我最终使用了这样的查询:
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')
}
读起来有点困难,但似乎可行。
关于ruby-on-rails - rails 查询: get all parent records based on latest child records,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599410/