开发者

Rails: Getting list of attributes with uniqueness validations from a model

开发者 https://www.devze.com 2023-03-29 02:42 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号