同一查询中的 ActiveRecord 'where not' 和 'where'

ActiveRecord 'where not' and 'where' in same query

我想建立一个 'waiting_on' 列表,列表中的用户满足两个条件:他们不属于当前拍卖 (User.where.not(auction: @auction)) 并且属于 current_game (User.where(game: current_game).

如何用在 ActiveRecord 中满足这两个要求的用户填充数组 @waiting_on

这是我的伪代码尝试:

@waiting_on = User.where not(auction: @auction) and game: current_game

更新:

目前我已经可以像这样工作了,但是有点难看:

users_in_auction = User.where(auction: @auction)
users_in_game = User.where(game: current_game)
@waiting_on = users_in_game - users_in_auction

我一直在尝试这个:User.where(game: current_game).where.not(auction: @auction),但是不参与拍卖的用户对 auction_idnil 值似乎搞砸了. SQL 查询输出似乎正是我所需要的:SELECT "users".* FROM "users" WHERE "users"."game_id" = 3 AND ("users"."auction_id" != 2)

您可以通过添加空检查在一个查询中完成:

User.where.not(auction: auction).or(User.where(auction: nil)).where(game: game)

这会产生这个 SQL,如果我没看错问题,我想这就是你想要的:

SELECT  "users".* FROM "users" 
WHERE (("users"."auction_id" != 7) OR "users"."auction_id" IS NULL) 
AND "users"."game_id" = 5