Rails: compare old value and new value during validation for editing

I want to create a custom validation function that will not allow the field to be left blank / zero only if the current field is not empty in the database. How to access database value (old value) in 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 will not accept the new empty value, but when creating a new object it will say: β€œIt cannot be empty after installation”, even if the old value has never been set.

+6
source share
1 answer

You can use ActiveModel :: Dirty . In your custom validation function, you can check if a field is empty 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 
+7
source

Source: https://habr.com/ru/post/924944/


All Articles