我有以下查询,它根据IDs数组提取一组结果

User.joins(:memberships).
     where(plan_memberships: { user_id: attendee_ids, plan_id: plan.id })

现在我想做另一个调用,它排除attendee_ids并与上面的结果进行concat,以保持结果的顺序,首先是与attendee_ids的结果,然后是其余的结果。
有没有一种方法可以保留基于某些id的结果的顺序,然后显示剩余的结果?

最佳答案

我认为在您的情况下,最好的方法是通过两个db查询分别检索结果。

common_scope = User.joins(:memberships).where(plan_memberships: { plan_id: plan.id })

excluded = common_scope.where.not(plan_memberships: { user_id: attendee_ids })
encluded = common_scope.where(plan_memberships: { user_id: attendee_ids })

all_sorted = excluded + encluded

Answer to additional question:
如果要检索特定数量的记录,可以这样做:
common_scope = User.joins(:memberships).where(plan_memberships: { plan_id: plan.id })
excluded_scope = common_scope.where.not(plan_memberships: { user_id: attendee_ids })
encluded_scope = common_scope.where(plan_memberships: { user_id: attendee_ids })

number = 3

excluded = excluded_scope.limit(number)
size = excluded.size

if size < number
  encluded = encluded_scope.limit(number - size)
  all_sorted = excluded + encluded
else
  all_sorted = excluded
end

09-20 17:02