0

私は4つのモデルを持っています:SchoolClass、、、、:TimetableLessonReporting

#  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 に答える