目前有4个表格:课程,部分,入学,学生。
我正在尝试在“注册”中添加验证,以使学生无法被注册到同一课程的多个部分中。我不知道如何实施此验证,因为课程与注册没有直接关系。
以下是需要进一步澄清的模型:
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
答案 0 :(得分:0)
您可以简单地将course_id
存储在Enrollment
上。此方法称为去规范化,这意味着您要避免在关系数据库中使用重复的内容。
答案 1 :(得分:0)
类似的事情应该起作用。只需将您的逻辑替换为your_logic_here
。
validate :multiple_enrollment
private
# Custom validator
def multiple_enrollment
if your_logic_here
errors.add(self.class.table_name, "Student is already enrolled in another section of this course.")
end
end