Posted 2 months ago. Visible to the public.

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

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:

Copy
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}>]

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

Copy
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}>]

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Judith Roth
Last edit:
2 months ago
by Judith Roth
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Judith Roth to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more