我有以下Query,它根据IDs
User.joins(:memberships).
where(plan_memberships: { user_id: attendee_ids, plan_id: plan.id })
现在我想做另一个排除attendee_ids
的调用,然后继续上面的结果,先用attendee_ids
保留结果的顺序,然后再保留结果。
有没有办法先根据某些ID保留结果的顺序,然后显示剩余的结果?
答案 0 :(得分:1)
您可以尝试注入一些SQL来涵盖您的排除案例。
User.joins(:memberships).
where(plan_memberships: { user_id: attendee_ids, plan_id: plan.id }).
where('plan_memberships.user_id not in (?)', banned_user_ids)
注意:根据您选择的数据库,这可能会有所不同
答案 1 :(得分:1)
我认为在您的情况下,最好的方法是通过两个数据库查询单独检索结果。
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
答案 2 :(得分:1)
如果您使用的是MySql,则可以选择根据数组中的ID保留订单。
field(user_id, [array of ids])
有关详情,请点击此处http://www.electrictoolbox.com/mysql-order-specific-field-values/