Search code examples
ruby-on-railsvalidationactivemodel

ActiveModel validation in separate File


Is there a way to fulfil the validation with ActiveModel in a separate file? There is the possibility of Custom Validations

class MyValidator < ActiveModel::Validator 
 … 
end

and call them with:validates_with MyValidator

But the default validation helper commands are not available in MyValidator.

All I need is to use: validates_length_of in a separate file and in best case called by various models.


Solution

  • I found quite an easy solution for that. Cause the custom validator class has to implement the method validate(record) the model is pass to the method as an ActiveRecord. All HelperMethods are avalible by calling inside this method:

    record.validate_presence_of :attribute