有没有一种方法可以验证给定模型对象中所有属性的真实存在?还是我必须列出每个属性presence: true
?
谢谢你的帮助。
要获取所有模型属性的数组,可以使用YourModel.attribute_names
。但是,您不能真正验证所有属性(例如id
,created_at
)的存在,因为在创建记录时,在验证期间这些属性将为空白。
class YourModel < ActiveRecord::Base
NON_VALIDATABLE_ATTRS = ["id", "created_at", "updated_at"] #or any other attribute that does not need validation
VALIDATABLE_ATTRS = YourModel.attribute_names.reject{|attr| NON_VALIDATABLE_ATTRS.include?(attr)}
validates_presence_of VALIDATABLE_ATTRS
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句