I have two models:
- lecture
- enrollment
The lecture has a capacity and a waiting list. If there’s an enrollment for a lecture, I’d like to validate if there are free seats available.
Created two helpers for that:
def availableSeats
return self.capacity - self.enrollments.confirmedEnrollments.count
end
def waitListAvailable
return self.waitListCapacity - self.enrollments.waitList.count
end
I thought about having the checks in the enrollment-controller, but it doesn’t work.
if(@lecture.availableSeats <= 0)
if(@lecture.waitListAvailable <= 0)
flash[:error] = "Enrolment not possible as the waiting list is full."
# interrupt and don't save, but how?
else
flash[:warning] = "You are on the waiting list."
@enrollment.confirmed = nil
end
else
@enrollment.confirmed = DateTime.now
end
Any ideas how this would work?
I’m assuming that your Enrollment model defines both the accepted students and those on the waiting list. I’m also assuming that the Lecture model has two attributes
available_seatsandavailable_wait_space, and the wait list is populated on a first-come basis and students are declined if the list is full, but the actual seats are confirmed or rejected by the lecturer manually.I’d certainly advise against doing anything at the controller level. This is a job for the models only.
By the way, don’t forget to set the default value for
statusto “waiting” in your migrations.