[英]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.
例如,我有一个模型 Person - 我想返回“Person”中具有唯一性约束的属性列表。 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.获取 Person 模型的唯一性验证器列表。 Each validator has an
@attributes
instance variable, and that's what you probably need.每个验证器都有一个
@attributes
实例变量,而这正是您可能需要的。
Building up on @eugen's answer , here is the code to list all attributes with a uniqueness validator:以@eugen 的回答为基础,以下是使用唯一性验证器列出所有属性的代码:
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.它返回一个符号数组,在末尾添加
.map(&:to_s)
以获得一个字符串数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.