Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 221
Matthew Hui Avatar asked Sep 09 '12 07:09

Matthew Hui


1 Answers

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
like image 122
Alex Ponomarev Avatar answered Sep 28 '22 22:09

Alex Ponomarev