Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use an existing Rails validator within a custom validation method?

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.

like image 292
nc. Avatar asked Aug 15 '14 19:08

nc.


1 Answers

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
like image 186
Samo Avatar answered Oct 30 '22 03:10

Samo