I am trying to use ActiveModel Validations & Callbacks on custom class.
class TestClass
include ActiveModel::Validations
define_model_callbacks :validate
attr_accessor :test_field
validates :test_field, presence: true # THIS IS CAUSING ISSUES!
before_validate do
test_field.try('upcase!')
end
def custom_validate!
run_callbacks :validate do
puts "Done"
end
end
end
But I am receiving the following error:
Failure/Error:
run_callbacks :validate do
...
end
NoMethodError:
undefined method `before_validate' for #<ActiveModel::Validations::PresenceValidator>
If I change callback name to something else than validate (e.g. validate_x) it works. Apparently validate is doing a bit more than I would expect. This error only happens if validates :test_field, presence: true is defined. For custom before_validate {} blocks it doesn't raise errors. Any idea how to fix this?