【问题标题】:Rails validate all attributes in objectRails 验证对象中的所有属性
【发布时间】:2015-11-30 14:28:54
【问题描述】:

有没有办法验证给定模型对象中所有属性的真实存在?还是我必须用presence: true 列出每个属性?

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails validation


    【解决方案1】:

    要获取所有模型属性的数组,您可以使用YourModel.attribute_names。但是,您无法真正验证所有属性(例如 idcreated_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
    

    【讨论】:

    • 太感谢了,我只需要输入 40 个属性就可以了。它是 validates_presence_of btw,如果你想编辑它?
    • validates_presence_of 是不推荐使用的语法。最好改用validates :list, :of, :attribute, :names, presence: true
    • 另外,您可以简单地通过数组差异来获取可验证字段的数组,而不是维护两个常量:YourModel.attribute_names - %w(id created_at modified_at)
    • @Andrei Horak validates_presence_of 未被弃用。 Rails 4.2.5 中没有提及弃用
    • @AbM 实际上是在 Rails 3 中,当时验证已移至 ActiveModel 并引入了 validates。该语法仍可使用,但validates 语法是首选语法。另请参阅有关“性感验证”的注释:guides.rubyonrails.org/…
    【解决方案2】:

    是的,您可以像这样在一行中添加所有属性:

    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。把它们都打字很累。
    • 多想这个并不优雅,最终你可以使用上面建议的属性数组。我个人坚持这一点,因为它是直截了当的。
    【解决方案3】:

    您可以使用.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多