Master table without related child record

Having a bit of a braindead day, can anyone help with this. I have three models: Player, Game, Prediction (Player has_many :games, :through => :prediction)

I want a named_scope that finds games that the current player hasn’t already predicted.

I started with something like this:

named_scope :without_prediction, lambda { |player_id|

{

:select => “games., predictions.”,

:joins => “LEFT JOIN predictions ON predictions.game_id = games.id”,

:conditions => “predictions.player_id IS NULL”

}

}

The problem is that this won’t work if ANY player has predicted that game’s result. So to be clear if there are games 1, 2 and 3 and players 10 and 11, player 10 has predicted results for all 3 games and player 10 has only predicted 1 and 2, I want a named_scope that returns game 3.

It seems like this is something I’ve done over and over again, but I just can’t get it clear in my head today.

Any ideas?

Cheers,

Andy

How about tackling it from the Player model like this

def unpredicted_games   Game.all - self.games end

Having a bit of a braindead day, can anyone help with this. I have three

models: Player, Game, Prediction (Player has_many :games, :through =>

:prediction)

I want a named_scope that finds games that the current player hasn’t already

predicted.

How about tackling it from the Player model like this

def unpredicted_games

Game.all - self.games

end

That’ll do me…

This is only a site for about 30-40 friends, so I’m not too bothered about efficiency.

Cheers,

Andy

Having a bit of a braindead day, can anyone help with this. I have three models: Player, Game, Prediction (Player has_many :games, :through => :prediction)

I want a named_scope that finds games that the current player hasn't already predicted.

I started with something like this:

named_scope :without_prediction, lambda { |player_id| { :select => "games.*, predictions.*", :joins => "LEFT JOIN predictions ON predictions.game_id = games.id", :conditions => "predictions.player_id IS NULL" } }

The problem is that this won't work if ANY player has predicted that game's result. So to be clear if there are games 1, 2 and 3 and players 10 and 11, player 10 has predicted results for all 3 games and player 10 has only predicted 1 and 2, I want a named_scope that returns game 3.

change the join so that the condition is predictions.game_id = games.id and predictions.player_id = ... and then change it so that the condition is predictions.id is NULL. Also be careful when doing something like games.*, predictions.* - identically named columns will shadow each other (eg id) which can lead to strange bugs

Fred