【问题标题】:Validating combination of columns not on the same table验证不在同一个表上的列组合
【发布时间】:2018-10-25 00:51:59
【问题描述】:

目前有 4 个表格:CourseSectionEnrollmentStudent

  • 一门课程有_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

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

您可以简单地将course_id 存储在Enrollment 上。这种方法称为去规范化,这意味着您在关系数据库中尝试避免重复的内容。

【讨论】:

    【解决方案2】:

    这样的事情应该可以工作。只需将您的逻辑替换为 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
    

    【讨论】:

    • 我相信我知道一般逻辑,但我不知道如何在语法上表达它。在添加由 student_id 和 section_id 组合而成的 ENROLLMENT 之前,请转到 SECTION 表并找到具有给定 section_id 的行。请注意此行中的 course_id,并确保没有学生的现有注册链接到此 course_id。这是否需要一个循环或者我可以做一些类似于if Section.where(:course_id =&gt; self.course_id, :student_id =&gt; self.student_id).present? 的事情来检查学生和课程之间的这种链接是否已经存在?
    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多