【问题标题】:Custom validations for non persisted model in Rails 4Rails 4 中非持久化模型的自定义验证
【发布时间】:2016-09-05 19:06:54
【问题描述】:

在阅读了(几乎)所有互联网之后,我需要您输入这个问题。

背景: 我有一个使用ActiveModel::Modelnon persisted Rails 4 model,根据其文档,包括ActiveModel::Validations

代码:

class GoodnessValidator < ActiveModel::Validator
  def validate(record)
    if record.first_name == "Evil"
      record.errors[:base] << "This person is evil"
    end
  end
end

class Person
  include ActiveModel::Model
  include ActiveModel::Validations

  validates_with GoodnessValidator
  attr_accessor :first_name
end

问题: 当我创建一个新的Person 时,p = Person.new(first_name: 'Evil') 应该被验证是一个“邪恶的人”。所以,我期望像p.errors 这样的错误访问器应该返回一个Hash 并包含所有错误。

但是,始终为空,p.errors 不会返回任何内容。绝不。

[102] pry(main)> p = Person.new(first_name: 'Evil')
=> #<Person:0x007fa0925809f0 @first_name="Evil">
[103] pry(main)> p.errors
=> #<ActiveModel::Errors:0x007fa09173ac88 @base=#<Person:0x007fa0925809f0 @errors=#<ActiveModel::Errors:0x007fa09173ac88 ...>, @first_name="Evil">, @messages={}>
[104] pry(main)> p.errors.full_messages
=> []
[105] pry(main)>

【问题讨论】:

    标签: ruby-on-rails validation ruby-on-rails-4 activemodel


    【解决方案1】:

    验证通常在您保存模型时触发。在您的情况下,您需要手动运行它们,然后检查错误:

    p = Person.new(first_name: 'Evil')
    unless p.valid? # runs the validations
      puts inspect p.errors
    end
    

    【讨论】:

    • 相反,还有一个invalid? 方法也会触发验证。
    • 哦,好点子!你是对的,验证器是一个必须在之前实例化并且有效的类?做吧
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    相关资源
    最近更新 更多