【发布时间】:2015-11-30 14:28:54
【问题描述】:
有没有办法验证给定模型对象中所有属性的真实存在?还是我必须用presence: true 列出每个属性?
感谢您的帮助。
【问题讨论】:
有没有办法验证给定模型对象中所有属性的真实存在?还是我必须用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
【讨论】:
validates_presence_of 是不推荐使用的语法。最好改用validates :list, :of, :attribute, :names, presence: true。
YourModel.attribute_names - %w(id created_at modified_at)。
validates_presence_of 未被弃用。 Rails 4.2.5 中没有提及弃用
ActiveModel 并引入了 validates。该语法仍可使用,但validates 语法是首选语法。另请参阅有关“性感验证”的注释:guides.rubyonrails.org/…
是的,您可以像这样在一行中添加所有属性:
validates :name, :login, :email, presence: true
【讨论】:
validates :orders,:diagnosis,:posterior_flattening, :circumference,:ap,:ml,:frontal_area,:parietal_lateral, :ear_position,:scan_file,:transfer_name,:modifications, :primary_mods,:top_opening,:side_opening,:chape_position, presence: true。把它们都打字很累。
您可以使用.attributes_names 方法获取Array 中的所有属性名称。
那么你要做的就是把这个array添加到validates_presence_of方法中。
示例:
class Model < ActiveRecord::Base
validates_presence_of attribute_names.reject { |attr| attr =~ /id|created_at|updated_at/i }
end
【讨论】: