Rails:列出创建所需的属性 [英] Rails: List Required Attributes For Create

查看:56
本文介绍了Rails:列出创建所需的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Model.new(< attributes here>)在Rails控制台中手动创建对象.有没有一种简单的方法可以列出一个模型要求我包括哪些属性,以使 .save 调用成功?

I am manually creating objects in the rails console using Model.new(<attributes here>). Is there an easy way to list out which attributes a model will require me to include in order for the .save call to succeed?

我正在运行Rails 4.2.3

I am running rails 4.2.3

推荐答案

您可以使用 Model.validators 获得一组验证器.您必须以某种方式对此进行解析,以提取这些在场验证信息,例如:

You can get an array of validators using Model.validators. You'll have to parse this in some way to extract those validations for presence, something like:

presence_validated_attributes = Model.validators.map do |validator|
  validator.attributes if validator.is_a?(ActiveRecord::Validations::PresenceValidator)
end.compact.flatten

这篇关于Rails:列出创建所需的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆