2017-06-14 45 views
2

如何使用ActiveRecord采集相关数据?rails pluck has_many through count

我想有两列返回,PatientProfile.namePatientProfile.recommendations.length

我试着用下面这个answer

class PatientProfile 
    has_many :recommendations 

PatientProfile.joins(:recommendations).select("patient_profiles.name as name, count(recommendation.id) as rec_count") 
+2

'计数(recommendation.id)'应'count(recommendations.id)''除非你将'推荐'模型的数据库表覆盖到'推荐' –

+0

@MichaelGorman这不适合我。我错过了什么吗? – user2954587

回答

1

你从answer输了.group
尝试此如果需要pluck(即阵列被期待作为输出):

PatientProfile 
    .joins(:recommendations) 
    .group(:id) 
    .pluck(:name, 'count(recommendations.id)') 

通过id分组,以避免非uniq的name为不同PatientProfile。根据您的应用程序逻辑的你可能会改变它.group(:name)
输出在2D阵列:

=> [['aa', 4], 
['bb', 2], 
['cc', 1]] 

如果你需要的关系作为输出,尝试:

PatientProfile 
    .joins(:recommendations) 
    .group(:id) 
    .select(:id, :name, 'count(recommendations.id) as rec_count') 
0

我觉得这应该工作:

res = ActiveRecord::Base.connection.execute(" 
    SELECT patient_profiles.name, count(patient_profile_id) AS rec_count 
    FROM patient_profiles INNER JOIN recommendations ON 
    recommendations.patient_profile_id = patient_profiles.id GROUP BY 
    patient_profile_id 
") 

res.to_a