Active Record where join table record doesn't exist

大憨熊 提交于 2019-12-30 14:10:34

问题


I am trying to get a list of all records that don't exist in a join table.

The models are User, Game and MarkedGame, where users can mark games as played. It's a many to many relationship:

User > MarkedGame < Game

What I want is a list of all games that haven't been marked by the user.

I know that I could do two separate queries and subtract them:

Game.all - current_user.games

But I don't like that this leaves me with an array rather than an Active Record relation object. Plus it seems like there should be a more performant way of doing it.

If there is no Active Record way of handling this, is there perhaps a SQL way? My raw SQL is not particularly strong so any help on that would be appreciated.

Thanks.


回答1:


That should do it. Returns all games that have not been marked by the current user.

Game.where('id not in (select game_id from marked_games where user_id = ?)', current_user.id)



回答2:


You can try the following:

Game.where.not(id: MarkedGame.where(user_id: current_user.id).pluck(:game_id))


来源:https://stackoverflow.com/questions/42193246/active-record-where-join-table-record-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!