获取必填字段列表

Ari*_*rif 3 ruby-on-rails

Post使用以下方法将模型的所有属性显示为 HTML 表头:

Post.column_names #=> ['id','name','status', 'created_at',....]
Run Code Online (Sandbox Code Playgroud)

但我只需要选择Post模型中需要的那些字段,即validates: presence: true

有没有办法选择必填字段?

Har*_*yay 5

尝试这个,

Post.validators
Run Code Online (Sandbox Code Playgroud)

它将返回模型中所有声明的验证器。喜欢 <ActiveModel::Validations::PresenceValidator:0x00000007b12568 @attributes=[..]

您可以迭代它或直接访问 Post.validators.first.attributes

希望对你有帮助。