简体   繁体   中英

How to get validation constraints of ApplicationRecord model in Rails?

I have a class that looks like:

class Account < ApplicationRecord
  validates :field, presence: true,
                    inclusion:{
                      in: %w[foo bar baz bla]
                    }
end

I need a method that returns the inclusion part of the validation for the field column. eg:

data = Account.validations_for(:field) # Or some similar magick method
data[:inclusion][:in] # => ['foo', 'bar', 'baz', 'bla']

Does something similar exist? If it was in an enum it could be simple, but I can't find the way to do it in this case.

If you do want to do this the fun Rails way:

Account.validators_on(:field).detect { |validator| validator.is_a? ActiveModel::Validations::InclusionValidator }.options[:in]

That'll return you an array of your fields.

Otherwise, while this isn't the black magic you're looking for, I'd adjust to the following to make this nice and flexible:

class Account < ApplicationRecord
  FIELD_OPTIONS = %w[foo bar baz bla].freeze

  validates :field, presence: true,
                    inclusion:{
                      in: FIELD_OPTIONS
                    }

Then you've got nice simple access via Account::FIELD_OPTIONS .

Either any use? Let me know how they suit / if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM