2017-08-16 46 views
0

我想知道是否有辦法在單個查詢中執行以下操作?在Rails中使用組時,如何返回填充的模型?

1) non_populated_models = PropertyPerson.select("property_people.id, count('items.recipient_person_id')").joins(:items).group('items.recipient_person_id, property_people.id') 
2) populated_models = PropertyPerson.where(id: [non_populated_models]) 

目前,通過查詢第一組只返回ID,並在ProperyPerson對象計數。假設模型中有15個字段,我不想將它們全部寫出來。有沒有一種方法可以在單個查詢中執行此操作?

回答

0

該連接將限制查詢到property_peopleitem和你你會得到額外的列作爲attr_reader

people = PropertyPerson.select("property_people.*, 
           count('items.recipient_person_id') as items_count") 
         .joins(:items) 
         .group("property_people.id") 

people.first.item_count