ActiveRecord'哪里没有'和'其中'在同一个查询中

时间:2017-11-29 03:22:20

标签: sql activerecord sinatra

我想建立一个'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)但是,不属于竞价的用户nil auction_id值的事实似乎搞砸了。 SQL查询输出似乎正是我所需要的:SELECT "users".* FROM "users" WHERE "users"."game_id" = 3 AND ("users"."auction_id" != 2)

1 个答案:

答案 0 :(得分:1)

您可以通过添加空检查在一个查询中执行此操作:

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