获取没有活动子项的父对象

时间:2017-07-05 06:26:51

标签: sql ruby-on-rails ruby postgresql ruby-on-rails-3

我有两个模型DoctorDoctorClinic,其中doctor has_many clinics

doctor.rb:

has_many :clinics, class_name: 'DoctorClinic', dependent: :destroy

doctor_clinic.rb

belongs_to :doctor

DoctorClinicdoctor_id和布尔active字段。

我想要的是什么:

我希望得到所有doctors没有任何有效(active字段为true)诊所的active。如果医生有两个诊所,其中一个是有效的,另一个是无效的,那么就不应该选择医生。

如果,

将选择医生记录
  • 根本没有诊所
  • 如果有任何诊所,但所有诊所都处于非活动状态,即所有诊所都有false scope :incomplete_doctors, -> { includes(:clinics) .where("( doctor_clinics.id IS NULL ) OR ( doctor_clinics.id IS NOT NULL AND doctor_clinics.active=?)", false ) }

如果,

,将不会选择医生
  • 那里有活跃的诊所。

到目前为止我尝试过的事情:

尝试1:

scope :incomplete_doctors, -> { where("id NOT IN (?)", self.includes(:clinics)
                            .where("( doctor_clinics.doctor_id IS NULL ) OR
                                      ( doctor_clinics.doctor_id IS NOT NULL AND
                                          doctor_clinics.active=?)", false )
                            .select(:id))
                            }

尝试2:

SELECT "doctors".* FROM "doctors"
  LEFT OUTER JOIN "doctor_clinics" ON "doctor_clinics"."doctor_id" = "doctors"."id"
  WHERE ( ( doctor_clinics.id IS NULL ) OR
          ( doctor_clinics.id IS NOT NULL AND
              doctor_clinics.active='f'))
  GROUP BY doctors.id
    HAVING 'true' <> ANY(array_agg(DISTINCT doctor_clinics.active::TEXT));

尝试3:

def active_clinics
  clinics.active_clinics # active_clinics is a scope in Clinic model while give all active clinics
end

def self.incomplete_doctors
  (Doctor.all.map { |d| d unless d.active_clinics.present? }).compact
end

成功:

我能够使用以下方法实现所需的输出,但我想使用SQL查询来实现此目的。

#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))

1 个答案:

答案 0 :(得分:1)

像这样的东西应该在纯SQL

中完成
public void openNumbers (View view) {
    Intent numbers = new Intent(MainActivity.this, NumbersActivity.class);
    startActivity(numbers);
}

您应该可以将其与SELECT * FROM doctors WHERE NOT EXISTS ( SELECT 1 FROM doctor_clinics WHERE doctor_clinics.doctor_id = doctors.id AND doctor_clinics.active = true )

一起使用
find_by_sql

没有Rails 3项目来实际测试它; - )