我有两个类(class)
class Patient < ActiveRecord::Base
belongs_to :camp
has_many :vaccinations
end
class Vaccination < ActiveRecord::Base
belongs_to :patient
end
每个疫苗接种都有名为 vaccine_id 的成员。 “完整”疫苗接种包括一组(比方说)6 种不同的疫苗,:name
s = {A,B,C,D,E,F}。
患者接种了很多疫苗,我想要一份所有接受“完整”疫苗接种的患者的报告。我可以使用 SQL 或 ActiveRecord 查询来获取此患者列表吗?
最佳答案
也许是这样的:
# in patient.rb
scope :with_completed_vaccinations, ->(number) {
joins(:vaccinations).group('patients.id').
having('COUNT(vaccinations.name) >= ?', number)
}
有了这个scope
,您就可以编写如下查询:
Patient.with_completed_vaccinations(6)
关于sql - 根据一组相关记录的条件获取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29786317/