Felipe Maion
Felipe Maion

Reputation: 351

How to use .where and check a self condition?

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

Answers (1)

Sujan Adiga
Sujan Adiga

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

Related Questions