Rails Validation - Maximum Database Records
I have a rails project using an active record and I was wondering if there is a validation helper for the maximum number of individual records. For example, if you had a form view and only want to say 2 and you just need the first 2 to be stored in the table, how would you do that?
I read the manual and took a look at the numbers and so on, but that's not exactly what I'm looking for. I tried to write my own validation method in the model, but I'm guessing there is a validation helper that makes this easier:
def validatePassengerNumber
if self.passengers.length > 2
# unsure on how to refuse new data access to database
end
end
source to share
Add an error to the database after checking to return true and it will prevent saving to the database.
def validate_passenger_number
self.errors.add(:base, "exceed maximum entry") if self.passengers.length > 2
end
Call this custom check on the appropriate model.
validate :validate_passenger_number, on: :create
source to share
No built-in validation; at least I haven't met anyone. But here's a way to enforce this type of validation:
def max_passengers
if self.passengers.count > 2
errors.add_to_base("There should not be more than 2 passengers.")
end
end
And then you can use that check to put a check on the number of passengers.
source to share