【问题标题】:Rails ActiveRecord query to select object by the number of related objects [duplicate]Rails ActiveRecord查询通过相关对象的数量选择对象[重复]
【发布时间】:2020-07-07 04:19:39
【问题描述】:

我有两个模型:

# game.rb

has_many :players, class_name: 'User'

# user.rb`

belongs_to :game

我想做Game.includes(:players).select { |game| game.players.count == 1 } 有AR查询,你能指点一下吗?提前致谢!

【问题讨论】:

    标签: ruby-on-rails ruby postgresql activerecord


    【解决方案1】:

    rails 3 getting the count of the records that have more than one associate records (has_many) 应该可以帮助您。他们给出的解决方案是:

    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-clause entry for table "players"
    • 我已经编辑了答案 - 没有意识到课程是用户
    猜你喜欢
    • 2016-05-29
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多