【发布时间】:2018-10-25 00:51:59
【问题描述】:
目前有 4 个表格:Course、Section、Enrollment、Student。
- 一门课程有_many Sections
- Sections 和 Students 共享多对多关系,其中 Enrollment 是联接表
我正在尝试在 Enrollment 中添加验证,以便学生无法注册到同一课程的多个部分。我不知道如何实施此验证,因为 Course 与 Enrollment 没有直接关系。
以下是进一步说明的模型:
class Course < ActiveRecord::Base
has_many :sections
end
class Section < ActiveRecord::Base
belongs_to :course
has_many :enrollments
has_many :students, through :enrollments
end
class Enrollment < ActiveRecord::Base
validate :noDuplicateCourses
def noDuplicateCourses
if #TRYING TO FIGURE OUT HOW TO EXPRESS THE LOGIC HERE
errors.add(:student_id, 'Already enrolled in a different section of this course')
end
end
belongs_to :section
belongs_to :student
end
class Student < ActiveRecord::Base
has_many :enrollments
has_many :sections, through :enrollments
end
【问题讨论】:
-
如果您只编写自己的验证,这非常简单。 guides.rubyonrails.org/…
标签: ruby-on-rails ruby-on-rails-4