I want to create a custom validation function that will not allow a field to be saved empty/nil only if the current field is not empty in the database. How can I access the database value (old value) in the validation function? I can access the new value using self.name_of_field.
This is what I have right now
validate :image_remote_url_change
def image_remote_url_change
if self.image_remote_url.blank? and self.image_remote_url_changed?
errors.add(:field, "can't be blank once set")
return false
end
end
Right now if I try to edit an existing object, it won't accept a new value of empty but when creating a new object it will say "can't be blank once set" even though the old value was never set.
You can take advantage of ActiveModel::Dirty. In your custom validation function you can check if field is blank and if it has changed:
validate :custom_validation_function
def custom_validation_function
if self.field.blank? and self.field_changed?
errors.add(:field, "can't be blank once set")
return false
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With