50

How cat I get list of validations defined in model

Example:

class ModelName
  validates_presence_of :field_name
  validates_inclusion_of :sex, :in => %w(M F)
end

I need Hash like:

{:field_name => 'required', :sex => 'Must be in: M, F'}
manzhikov
  • 3,778
  • 3
  • 20
  • 22

5 Answers5

116

You don't need a plugin for basic needs.

You can do this to get a hash of all validators.

ModelName.validators

If you want to get the validators for a specific field :

ModelName.validators_on(:attribute)
Nicolas Blanco
  • 11,164
  • 7
  • 38
  • 49
  • Cool! It's better, than plugin – manzhikov Oct 29 '10 at 13:53
  • 3
    Just a note, this is only available in Rails 3. For earlier rails apps, the plugin is the way to go. – Jaime Bellmyer Oct 29 '10 at 16:20
  • 1
    How can I get this if I am using a custom validate method like `validate :check_name_blank` Inside this method I am checking name is present and some other stuffs. So while I am doing `ModelName.validators_on :name`, I am getting an empty array. – Abhi Nov 18 '14 at 13:01
4

This code yields an array of required fields. It should be adaptable to your needs.

@required_fields = []
ModelName.validators.each do |v|
  @required_fields << v.attributes.first if v.kind == :presence
end
Jussi Hirvi
  • 565
  • 3
  • 6
1

If you add validations dynamically in your models, you can use the instance to list the validations:

product = Product.new
product.singleton_class.validators_on(:price)
#=> [#<ActiveModel::Validations::PresenceValidaton>]

Tested in Rails 5.2.

vinibrsl
  • 6,563
  • 4
  • 31
  • 44
0

Looks like there's no native way to do it, but a quick Google (for "rails reflect validations") turns up this plugin.

Chowlett
  • 45,935
  • 20
  • 116
  • 150
0

This code work for me:

ModelName.validators_on(:sex).first.options[:in]

answer: ["M","F"]

You want something like this:

field = :sex
sexs = ModelName.validators_on(field).first.options[:in]
hsh = {}
hsh[:field_name] = (ModelName.validators.grep(ActiveRecord::Validations::PresenceValidator).flat_map(&:attributes).include?(field)) ? 'required': 'optional'
hsh[field] ="Must be in: #{sexs.to_sentence(two_words_connector: ', ')}"

answer hsh: {:field_name=>"required", :sex=>"Must be in: M, F"}

I use Rails 6.1.4.1

Developer
  • 417
  • 2
  • 7
  • 17