Ruby on rails Rails ActiveRecord查询,根据相关对象的数量选择对象

Ruby on rails Rails ActiveRecord查询,根据相关对象的数量选择对象,ruby-on-rails,ruby,postgresql,activerecord,Ruby On Rails,Ruby,Postgresql,Activerecord,我有两种型号: # game.rb has_many :players, class_name: 'User' 及 我想做Game.includes(:players)。选择{| Game | Game.players.count==1} 对于AR查询,请您提供建议?提前谢谢 应该能帮到你。他们给出的解决方案是: Account.joins(:users).select('accounts.id').group('accounts.id').having('count(users.id) &

我有两种型号:

# game.rb

has_many :players, class_name: 'User'

我想做
Game.includes(:players)。选择{| Game | Game.players.count==1}
对于AR查询,请您提供建议?提前谢谢

应该能帮到你。他们给出的解决方案是:

Account.joins(:users).select('accounts.id').group('accounts.id').having('count(users.id) > 1')
在您的情况下,请尝试:

Game.joins(:players).select('games.id').group('games.id').having('count(users.id) = 1')

谢谢你的回复!不幸的是,它对我不起作用,错误:
PG::UndefinedTable:error:missing FROM子句条目为表“players”
我编辑了答案-没有意识到该类是用户
Game.joins(:players).select('games.id').group('games.id').having('count(users.id) = 1')