2017-08-16 49 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