I don't see this as an association because an association is generally something where you have a foreign key pointing to something, but in this case you have no foreign key. I see this as more of an instance attribute which I would do like this:
def unviewed_games
Game.all(:conditions => ["id NOT IN (SELECT game_id FROM game_views WHERE user_id = ?", self.id])
end
You could do a NOT IN (1,2,3)
by querying the viewed games, but that can get very inefficient, very very fast. This is one time I would write out the SQL. I would also do one more thing:
def unviewed_games
return @unviewed_games if defined(@unviewed_games)
@unviewed_games = Game.all(:conditions => ["id NOT IN (SELECT game_id FROM game_views WHERE user_id = ?", self.id])
end
That will store it in an instance variable for the length of the request, and save you the multiple database hits. You can do ||=
, but if somehow you were to get a nil
, then you would still query the database multiple times. Rails should cache, but call me paranoid.
Hope this helps!