[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.


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

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
Score: 1

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

product = Product.new
#=> [#<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:


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

More Related questions