Reputation: 489
Really weird, but I made a custom validation in my model. When multiple validations are triggered, the form is not saving and the custom validation error show in the form.
However....
When the custom validation is the only validation that is triggered, the form saves incl. the data that is invalid?
extra_guest model
validate :no_dates_overlap
def no_dates_overlap
ranges = [] # cache proccessed date ranges
# iterate over all extra_guest_prices
extra_guest_prices.each do |egp|
if ranges.any? { |rng| rng.include?(egp.start_date) || rng.include?(egp.end_date) }
# if a previous range includes this dates, add the error and break the loop
egp.errors.add(:start_date, "Dates overlap")
break
else
# else, cache it and check the next
ranges << (egp.start_date..egp.end_date)
end
end
end
end
Upvotes: 1
Views: 162
Reputation: 4709
From rails guide
The valid? method will verify that the errors collection is empty, so your custom validation methods should add errors to it when you wish validation to fail
You need to add error to record's errors array. So change your code as below:
errors.add(:start_date, "Dates overlap")
Upvotes: 1
Reputation: 74
you cannot add errors in extra_guest_prices. You should add the error in extra_guest.
Try:
self.errors.add(:base, "Dates overlap")
Upvotes: 2