如何查詢has_many :through
以查看哪些記錄在另一端具有空關聯? (我使用的軌道5)查詢空has_many通過
class Specialty
has_many :doctor_specialties
has_many :doctor_profiles, through: :doctor_specialties
class DoctorProfile
has_many :doctor_specialties
has_many :specialties, through: :doctor_specialties
class DoctorSpecialty
belongs_to :doctor_profile
belongs_to :specialty
我可以列舉在Specialty
做到這一點,但我希望做一個SQL查詢。
Specialty.includes(:doctor_profiles).all.select{|x| x.doctor_profiles.length == 0 }
從Rails 5開始,您可以使用'left_outer_joins'而不是'includes' - 請參閱http://guides.rubyonrails.org/active_record_querying.html#left-outer-joins – gmcnaughton