我有两个模型Doctor
和DoctorClinic
,其中doctor
has_many
clinics
。
doctor.rb:
has_many :clinics, class_name: 'DoctorClinic', dependent: :destroy
doctor_clinic.rb
belongs_to :doctor
DoctorClinic
有doctor_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))
答案 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项目来实际测试它; - )