Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record where join table record doesn't exist

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.

like image 787
Danny Santos Avatar asked Nov 29 '25 11:11

Danny Santos


2 Answers

You can try the following:

Game.where.not(id: MarkedGame.where(user_id: current_user.id).pluck(:game_id))
like image 97
potashin Avatar answered Dec 02 '25 00:12

potashin


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)
like image 28
Eyeslandic Avatar answered Dec 02 '25 00:12

Eyeslandic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!