I am programming a booking system.
I want my users to be able to book only one (or a defined number of) resources at a time. However, I do not want to remove “past” reservation for my database, since it will be used for invoicing purposes. On reservation creation, I need to validate that a user has not exceeded its reservation quota, which means has not more than “quota” reservations in the future.
class User < ActiveRecord::Base
has_many :reservations
def active_reservations
#maybe worth to rewrite with a "find"?
my_list = []
reservations.each do |reservation|
if (not reservation.past?)
my_list.push(reservation)
end
return my_list
end
class Reservation < ActiveRecord::Base
belongs_to :user
validate :respect_user_quota
def past?
return (date < Date.now)
def respect_user_quota
if (user.active_reservations.count > user.quota)
errors.add(:user, "User quota exceeded!")
Is this the right way to implement this validation? What could be wrong there (I never see the error message). Should the quota validation be moved to the user class?
I would try and do this more simply and move the validation to user.