鉴于这些课程
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查询是什么?
答案 0 :(得分:2)
在ActiveRecord中查询以获取具有多个不完整FollowUp的所有帐户
只需join
follow_ups
到accounts
并按follow_ups.completed_at
过滤即可解决:
Account.joins(:follow_ups).where(follow_ups: { completed_at: nil })
如果您需要的不完整follow_ups
数量超过特定数字,那么GROUP BY
和HAVING
可能有所帮助:
Account
.joins(:follow_ups)
.where(follow_ups: { completed_at: nil })
.group(:id)
.having("COUNT(follow_ups.id) > 1")