ExiRe
ExiRe

Reputation: 4767

Rails 3 - validate through few models

I have 4 models: 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

How can i validate that each SchoolClass can have only 1 Reporting with type "checkpoint"?

Upvotes: 0

Views: 99

Answers (1)

evanbikes
evanbikes

Reputation: 4171

This gets super complicated because of the nesting associations. I would start by using a custom validation method.

in the SchoolClass model:

validate :only_one_reporting_checkpoint

and then the method:

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

There, I think that does it. If I understand your problem correctly.

Upvotes: 1

Related Questions