mdedetrich
mdedetrich

Reputation: 1889

Using a default validator in custom validations

What I am basically trying to do is to create a custom validation which calls a RoR default validation with specific options to try and reduce boilerplate (and have this validation to be used globally by all models)

The way to do custom validations on a certain field in RoR is by using the validates_each method, like so

class SelectBooleanValidator < ActiveModel::EachValidator

  def validate_each(record,attr,value)
    #do validation here
  end

end

What I am trying to do is to call the inclusion validator method within the validator_each, so that the select_boolean validation (which I am implementing) just uses the :inclusion validator with certain options, i.e. I want to do something like this (note that this code doesn't actually work, but the below is what I am basically trying to do)

class SelectBooleanValidator < ActiveModel::EachValidator
  include ActiveModel::Validations
  def validate_each(record,attr,value)
    validates_with InclusionValidator, record,attr,value,  {:in => [true, false],:message=>'can\'t be blank'}
  end
end

And then I would (inside my model) just do this

validates :awesome_field, select_boolean:true

Instead of having to do this all the time

validates :awesome_field, :inclusion => {:in => [true, false], message: 'can\'t be blank'}

Upvotes: 0

Views: 110

Answers (1)

mikdiet
mikdiet

Reputation: 10038

class SelectBooleanValidator < ActiveModel::Validations::InclusionValidator
  def options
    super.merge(:in => [true, false], message: 'can\'t be blank')
  end
end

Upvotes: 1

Related Questions