我正在尝试与自定义范围创建return res.status(500).send({ message: 'some error' });
关联。问题是范围有has_many :through
和第3个模型,这似乎打破了关联。
这些是模型:
joins
我希望从课程中吸取学生的导师,但我得到class Student < ApplicationRecord
has_many :lesson_applications, through: :lesson_requests
has_many :lessons, through: :lesson_applications
has_many :scoped_lessons, -> { custom_scope }, through: :lesson_applications, source: :lesson
has_many :tutors, through: :scoped_lessons # Broken association
end
class Lesson < ApplicationRecord
belongs_to :lesson_application
has_one :tutor, through: :lesson_application
has_one :time_range, as: :time_rangeable
scope :custom_scope, (lambda {
joins(:time_range).where('time_ranges.attribute BETWEEN ? AND ?', value1, value2)
})
end
class LessonApplication < ApplicationRecord
belongs_to :lesson_request
belongs_to :tutor
has_one :lesson
end
class Tutor < ApplicationRecord
has_many :lesson_applications
has_many :lessons, through: lesson_applications
end
class TimeRange < ApplicationRecord
belongs_to :time_rangeable, polymorphic: true
end
。在生成的查询中可以看到明显的错误。
我执行missing FROM-clause entry for table 'time_ranges'
时生成的查询是:
student.tutors
我临时使用的方法是:
SELECT "tutors".* FROM "tutors" INNER JOIN "lesson_applications" ON "tutors"."id" = "lesson_applications"."tutor_id" INNER JOIN "lessons" ON "lesson_applications"."id" = "lessons"."lesson_application_id" INNER JOIN "lesson_applications" "lesson_applications_tutors" ON "lessons"."lesson_application_id" = "lesson_applications_tutors"."id" INNER JOIN "lesson_requests" ON "lesson_applications_tutors"."lesson_request_id" = "lesson_requests"."id" WHERE "lesson_requests"."student_id" = $1 AND (time_ranges.start BETWEEN '2018-04-11 20:27:34.798992' AND '2018-04-11 20:27:34.799090') LIMIT $2
我正在使用带有Rails 5.1.6的ruby 2.5.1
提前谢谢。
编辑:有些关联错了。