2012-12-14 40 views
1

說我有2種型號:如何使用ActiveRecord獲取有2條記錄的記錄列表?

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

我想誰恰好有2個地址的所有的人。有沒有一個容易的ActiveRecord/Arel的方式與子查詢做到這一點?我不想使用counter_cache來做到這一點。

回答

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 
+2

我會爲該查詢添加'select('people。*')'以擺脫與地址相關的屬性。 – skalee

+0

更新,謝謝;) – MrYoshiji

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 
相關問題