Jasper van den Berg
Jasper van den Berg

Reputation: 134

Rails: Validate if there are new relations

I am creating a student enrollment system and I am having a problem. I want to make sure students cannot enroll a course that has been closed, the problem is: how can i check if there are new student relations created for my course? This is my validation:

class Course < ActiveRecord::Base
  has_and_belongs_to_many :students, class_name: 'User', join_table: 'following_classes_students'
  validate :cannot_enroll_old_course

  def cannot_enroll_old_course
    if end_enrollments <= Date.today && self.students.last.new_record?
      errors.add(:base, 'Cannot enroll a closed course')
    end
  end
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :following_classes, class_name: 'Course', join_table: 'following_classes_students'
end

Of course the student isn't a new_record? so this code does not work. What I need is something like new_child? or something.

Upvotes: 0

Views: 51

Answers (1)

bo-oz
bo-oz

Reputation: 2872

I guess you also have an enrollment model and you handle the enrollments from your EnrollmentController. So when you are saving an enrollment you know about the student and the course. In this model you check that the course is still open for enrollment. You can do this by creating a relationship that contains the requirement.

Generate this model with:

rails g model Enrollment student:references course:references

class Enrollment
  belongs_to :student
  belongs_to :course
  validate :valid_course

  def valid_course
    self.course.active
  end
end

and in your Course model add an acitve column or method:

class Course
  has_many :enrollments
  has_many :students, through: :enrollments

  def active
    # check for active and return true or false
  end
end

Upvotes: 1

Related Questions