I would like to create a custom validation method within my model and use some existing validators (specifically, validates_numericality_of) within the custom validation method.
Is this possible? If so, how do I do it?
For some context: We are using a non-ActiveRecord ORM that has an attribute that is a Hash. I want to perform validations on stuff inside the hash. If there is a way to do that, like validates_numericality_of :my_attribute.:subattribute or something, that would be fine too.
Thank you.
I believe this should work for you.
class MyCustomValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    validator = ActiveModel::Validations::NumericalityValidator.new(
      :greater_than_or_equal_to => options[:min],
      :less_than_or_equal_to => options[:max],
      :attributes => value[:some_attribute]
    )
    validator.validate(record)
  end
end
You could use it like this:
validates(
  :my_pseudo_attribute,
  :my_custom => {
    :min => 0,
    :max => 100
  }
)
def my_pseudo_attribute
  {
    :some_attribute => 'foo'
  }
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