Rails 4 中非持久模型的自定义验证

Custom validations for non persisted model in Rails 4

阅读(几乎)所有互联网内容后,我需要您输入此问题。

上下文: 我有一个 non persisted Rails 4 model using ActiveModel::Model that, according to its documentation, includes 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') 应该被验证为 "evil person"。所以,我希望有一个像 p.errors 这样的错误访问器,它应该 return 我一个 Hash 并包含所有错误。

但是,总是空的,p.errors不要return什么都没有。绝不。

[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)>

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

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