0

我有 4 个模型:SchoolClass, Timetable, Lesson, Reporting:

#  class_code :string(255)
class SchoolClass < ActiveRecord::Base
  has_many :timetables
end

class Timetable < ActiveRecord::Base
  belongs_to :school_class
  has_many :lessons
end

class Lesson < ActiveRecord::Base
  belongs_to :timetable
  has_one :reporting
end

# report_type  :string(255)
class Reporting < ActiveRecord::Base
  belongs_to :lesson

  validates :report_type,
              :presence  => true,
              :inclusion => { :in => %w(homework checkpoint)}
end

我如何验证每个“检查点”类型SchoolClass只能有 1 个?Reporting

4

1 回答 1

1

由于嵌套关联,这变得非常复杂。我将从使用自定义验证方法开始。

在 SchoolClass 模型中:

validate :only_one_reporting_checkpoint

然后方法:

def only_one_reporting_checkpoint
  timetables = self.timetables
  reporting_checkpoint = nil
  timetables.each do |t|
    t.lessons.each do |l|
      reporting_checkpoint = true if l.reporting.report_type == "checkpoint"
    end
  end
  if reporting_checkpoint == true         
    errors.add(:reporting, "exception raised!")
  end
end

在那里,我认为可以。如果我正确理解您的问题。

于 2012-05-25T17:55:23.747 回答