Rails: Getting list of attributes with uniqueness validations from a model
Just wondering if it's possible to return a list of all attributes which possess a uniqueness validation? For example, I have a model Person - I'd like to return a list of the attributes in 'Person' which have开发者_运维问答 a uniqueness constraint. Any ideas?
You can do something like
Person.validators.select { |v| v.is_a?(ActiveRecord::Validations::UniquenessValidator) }
to get the list of uniqueness validators for the Person model. Each validator has an @attributes
instance variable, and that's what you probably need.
Building up on @eugen's answer, here is the code to list all attributes with a uniqueness validator:
self.class.validators.collect do |validator|
validator.attributes if validator.is_a?(ActiveRecord::Validations::UniquenessValidator)
end.flatten.compact.uniq
It returns an array of symbols, add .map(&:to_s)
at the end to get an array of strings.
精彩评论