Read more

Rails: How to list all validations on a model or an attribute

Judith Roth
September 23, 2020Software engineer at makandra GmbH

If a model inherits from others or uses many concerns / traits, it might be hard to see in the code which validators it has.
But fortunately there's a method for that:

irb(main):002:0> pp UserGroup.validators
[#<ActiveModel::Validations::InclusionValidator:0x00007f55efff97a8
  @attributes=[:deleted],
  @delimiter=[true, false],
  @options={:in=>[true, false], :allow_nil=>false}>,
 #<ActiveModel::Validations::InclusionValidator:0x00007f55f15748d0
  @attributes=[:cancelled],
  @delimiter=[true, false],
  @options={:in=>[true, false], :allow_nil=>false}>,
 #<ActiveRecord::Validations::PresenceValidator:0x00007f55f023d898
  @attributes=[:partner],
  @options={:message=>:required}>,
 #<ActiveRecord::Validations::PresenceValidator:0x00007f55f023c6f0
  @attributes=[:partner_id, :name],
  @options={}>,
 #<ActiveRecord::Validations::UniquenessValidator:0x00007f55f1417e88
  @attributes=[:name],
  @klass=UserGroup (call 'UserGroup.connection' to establish a connection),
  @options={:case_sensitive=>true, :scope=>:partner_id}>,
 #<ActiveModel::Validations::NumericalityValidator:0x00007f55f1415200
  @attributes=[:user_count_limit],
  @options={:greater_than_or_equal_to=>0, :allow_nil=>true}>]

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

You can also list all validators on a given attribute of a model:

irb(main):003:0> pp UserGroup.validators_on(:name)
[#<ActiveRecord::Validations::PresenceValidator:0x00007f55f023c6f0
  @attributes=[:partner_id, :name],
  @options={}>,
 #<ActiveRecord::Validations::UniquenessValidator:0x00007f55f1417e88
  @attributes=[:name],
  @klass=UserGroup (call 'UserGroup.connection' to establish a connection),
  @options={:case_sensitive=>true, :scope=>:partner_id}>]
Posted by Judith Roth to makandra dev (2020-09-23 14:14)