如何使用ActiveRecord获取具有2个相关记录的记录列表?

时间:2012-12-14 17:22:12

标签: ruby-on-rails ruby activerecord arel

说我有2个型号:

class Person < ActiveRecord::Base
  has_many :addresses
end
class Address < ActiveRecord::Base
  belongs_to :person
end

我希望得到所有拥有2个地址的人。使用子查询是否有一个简单的ActiveRecord / Arel方法?我不想使用counter_cache来做它。

2 个答案:

答案 0 :(得分:3)

这对我有用(使用Rails 3,PostGreSQL):

Patient.joins(:interventions).group('patients.id').having('count(patient_interventions.id) = 2')

在您的情况下,以下内容应该返回恰好有2个地址的人员

Person.includes(:addresses)
      .select('persons.*')
      .group('persons.id')
      .having('count(addresses.id) = 2')
# Note use :joins instead of :includes if you don't want the addresses data

答案 1 :(得分:0)

@MrYoshiji的回答很好,但有时您可能更喜欢做两个查询。另一种方法:

person_ids = Address.select('person_id, count(person_id) as cnt').group('person_id').having('cnt = 2').pluck(:person_id)
Person.find person_ids
相关问题