您可以执行以下查询,以让您的用户按他们拥有的事件数排序:
@users = User.
select("users.*, COUNT(event_logs.id) as event_logs_count").
joins('LEFT JOIN event_logs ON event_logs.user_id = users.id').
group('users.id').
order('event_logs_count DESC')
您应该使用 a LEFT JOIN
,因为您希望包括没有任何事件的用户。
如果您要将其编写为范围:
scope(:highest_completed_events, {
select: 'users.*, COUNT(event_logs.id) as event_logs_count',
joins: 'LEFT JOIN event_logs ON event_logs.user_id = users.id',
group: 'users.id',
order: 'event_logs_count DESC'
})
@users = User.highest_completed_events
为了按特定状态过滤事件,只需使用where()
.
@users = User.
select("users.*, COUNT(event_logs.id) as event_logs_count").
joins('LEFT JOIN event_logs ON event_logs.user_id = users.id').
where('event_logs.status = ?', STATUS_COMPLETE).
group('users.id').
order('event_logs_count DESC')
顺便说一句,有时您会遇到 ActiveRecordselect()
在执行类似@users.count
. 我通常做的是将这种事情嵌套在自定义from()
语句中。
_from = User.
select("users.*, COUNT(event_logs.id) as event_logs_count").
joins('LEFT JOIN event_logs ON event_logs.user_id = users.id').
group('users.id').
order('event_logs_count DESC').to_sql
@users = User.from("(#{_from}) as users")
@users.count # will work