has_many通过关联找到Doctor.id的计数

时间:2019-06-04 06:27:06

标签: ruby-on-rails ruby pagination ruby-on-rails-5

我正在尝试获取count(physician.id),但是在rails中却出现了错误。

class Physician < ApplicationRecord
 has_many :appointments
 has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
 belongs_to :physician
 belongs_to :patient
end

class Patient < ApplicationRecord
 has_many :appointments
 has_many :physicians, through: :appointments
end

而我在这里做的是:

patients_count = Patient.joins(:physicians).includes(:physicians).select('count(physician.id) as count').group('patients.id').paginate(page: params[:page], per_page: 25) 

我遇到此错误,"PG::SyntaxError: ERROR: syntax error at or near "as" LINE 1: ...CT COUNT(DISTINCT count(physician.id) as count)"

不确定分页是否引起此问题,如何解决?

2 个答案:

答案 0 :(得分:0)

在模型上使用属性时,查询中的属性应为复数形式 即用physicians.id代替physician.id

patients_count = Patient.joins(:physicians)
                            #.includes(:physicians)
                            .group('patients.id')
                            .select("count(physicians.id) as count")
                            .paginate(page: params[:page], per_page: 25)

答案 1 :(得分:0)

查询中存在拼写错误。另外,我认为在这种情况下我们不需要includes。您被迫加入两次

patients_count = Patient.joins(:physicians).select('count(physicians.id) as count').group('patients.id').paginate(page: params[:page], per_page: 25)