我有模型BatchClass和SubjectTeacherBatchClass,它们的属性如下。
class SubjectTeacherBatchClass < ApplicationRecord
belongs_to :batch_class
belongs_to :user, optional: true
belongs_to :shift
belongs_to :session_batch
end
和
class BatchClass < ApplicationRecord
has_many :subject_teacher_batch_classes
has_many :subjects, through: :subject_teacher_batch_classes
has_many :teachers, source: :user, foreign_key: 'user_id', through: :subject_teacher_batch_classes
end
我想访问batch_class.teachers,但要使用自定义属性,例如。
batch_class.teachers.where(session_batch_id: session_batch.id, shift_id: current_shift.id)
问题在于session_batch_id
和shift_id
不是User
类(别名老师)的属性,而是SubjectTeacherBatchClass
类的属性。 (直通类)
是否有更好的方法可以使批处理班的老师传递默认属性(session_batch和shift)
答案 0 :(得分:0)
类似于https://stackoverflow.com/q/18799934/1154044的问题,与您的问题类似。
根据您的模型,您可以尝试此查询
batch_class.teachers.
references(:subject_teacher_batch_classes).
where(subject_teacher_batch_classes: {
session_batch_id: session_batch.id, shift_id: current_shift.id
})