如何查询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