Alex Rivera | Logout

Rails: Compare old value and new value during validation for edit

Asked 2012-09-09T07:51:55.813
8

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.

Edit
Report

1 Answer

11

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
answered 2012-09-09T08:09:58.683

Your Answer