ActiveRecord:按照has_many的计数分组:通过模型

时间:2018-04-21 05:56:33

标签: ruby-on-rails ruby activerecord

鉴于这些课程

class Account < ApplicationRecord
  has_many :team_memberships
  has_many :follow_ups, through: :team_memberships
end

class TeamMembership < ApplicationRecord
  belongs_to :account
  has_many :follow_ups
end

class FollowUp < ApplicationRecord
  belongs_to :team_membership
  has_one :account, through: :team_membership
end

我正在寻找在ActiveRecord中查询的惯用方法,以获取具有多个不完整Account的所有FollowUp(即具有多个Account的{​​{1}} {{ 1}} FollowUp completed_at}。

使用Ruby但不完全编译为SQL的慢速方法是

nil

但是对于这个适当的ActiveRecord查询是什么?

1 个答案:

答案 0 :(得分:2)

  

在ActiveRecord中查询以获取具有多个不完整FollowUp的所有帐​​户

只需join follow_upsaccounts并按follow_ups.completed_at过滤即可解决:

Account.joins(:follow_ups).where(follow_ups: { completed_at: nil })

如果您需要的不完整follow_ups数量超过特定数字,那么GROUP BYHAVING可能有所帮助:

Account
  .joins(:follow_ups)
  .where(follow_ups: { completed_at: nil })
  .group(:id)
  .having("COUNT(follow_ups.id) > 1")