[ACCEPTED]-get validations from model-activemodel

Accepted answer
Score: 111

You don't need a plugin for basic needs.

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

ModelName.validators

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

ModelName.validators_on(:attribute)
Score: 3

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

@required_fields = []
ModelName.validators.each do |v|
  @required_fields << v.attributes.first if v.kind == :presence
end
Score: 1

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

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

Tested in Rails 5.2.

Score: 0

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

Score: 0

This code work for me:

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

answer: ["M","F"]

You want something 1 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

More Related questions