拒绝关联具有特定属性值的记录

Reject records where associations have specific attribute value

我有 3 个模型:

class Server
  has_many: games
end

class Game
  belongs_to: server
  has_many: players
end

class Player
  belongs_to: game
end

Player 模型有一个属性 valid 可能是 true/false

现在我想获得属于特定 servergames 的列表,但是在为 servergames 时我想拒绝所有 games 其中 只有 具有 players,属性 valid 设置为 true

任何 game 甚至有一个 player 属性 validfalse 的任何 game 都应该显示在结果中。

我可以通过以下方式进行:

@server.games.reject { |g| g.players.reject(&:valid).empty? } 

但这似乎非常低效。有没有更好的方法来实现?

您有两个选择:

选项 1 使用 INNER JOIN:

games_with_invalid_players = Game.joins(:players).where(players: { valid: false })
# add .distinct at the end if you want to remove the duplicated game records

选项 2 使用 sub-select:

game_ids = Player.where(valid: false).select(:game_id).distinct
games_with_invalid_players = Game.where(id: game_ids)