![](/img/trans.png)
[英]How to create records in has_many through association in rails 3.2
[英]How to retrieve records from a specific table using the ActiveRecord has_many through association in Rails 4?
使用来自RailsGuide的has_many:through关联示例,如何使用ActiveRecord选择没有预约的所有患者或医生?
2.4 has_many:通过协会 http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, through: :appointments
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :enrollments
has_many :courses, through: :enrollments
end
class Enrollment < ActiveRecord::Base
belongs_to :course
belongs_to :user
scope :registered, -> { where("enrolled = ?", true) }
scope :student, -> (student_id) { where("user_id = ?", student_id) }
end
class Course < ActiveRecord::Base
before_save :update_slug
has_many :enrollments
has_many :users, through: :enrollments
def update_slug
self.slug = title.parameterize
end
def to_param
slug
end
# scope :available, -> { where.not(id: Enrollment.pluck(:course_id)).uniq }
scope :available, -> (student_id) { where.not(id: Enrollment.pluck(:course_id)).uniq }
end
您可以做的最简单的事情是,首先从联接表/模型中选择所有ID,然后使用该列表从第二个查询中排除记录:
Physician.where.not(id: Appointment.pluck(:physician_id).uniq)
Patient.where.not(id: Appointment.pluck(:patient_id).uniq)
您也可以使用我个人更喜欢的纯SQL:
Physician.where("
not exists (select 1 from appointments
where appointments.physician_id = physician.id)
")
Patient("
not exists (select 1 from appointments
where appointments.patient_id = patient.id)
")
至于“我该如何根据签名的患者来过滤记录?”,那是什么意思?
Appointment.find_by(patient_id: 123).patient
Appointment.find_by(patient_id: 123).physician
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.