Reputation: 351
I want to get all the games that are not full, ie, has empty spot in the table.
The available number of spots is the nplayer
attribute of my model Game.
I have a helper to get the current number_of_players that are already in a game: number_of_players(game)
I am trying the following to show the games that have room space:
@opengames = Game.where("nplayer > ?", number_of_players(***game***))
My problem is: what should I use inside my helper number_of_game(xxxx).
How can I tell .where to check the game that it is trying to find? Is it possible or should I get all the games, and than compare one by one? Like:
@opengames = []
@games = Game.all
@games.each do |game|
if game.nplayer > number_of_players(game)
@opengames.push game
end
end
(Sorry if my explanation is not clear... english is not my native language)
Upvotes: 0
Views: 59
Reputation: 1371
You can try select
@opengames = Game.all.select { |game| game.nplayer > number_of_players(game) }
However it will be more cleaner if you can perform number_of_players
at db level only. For instance if games and decks are associated, you can perform
Game.where("`games`.`nplayer` > (SELECT COUNT(*) FROM `decks` WHERE `decks`.`game_id` = `games`.`id`)")
Upvotes: 1