【发布时间】:2011-12-07 12:25:28
【问题描述】:
在我的应用程序中,似乎根本没有运行 ActiveModel 验证。也就是说,无论数据实际上多么无效,它们总是返回 true(有效)。
class QueueItem
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user
field :appointment_time, type: DateTime, allow_nil: true
field :notes, type: String, allow_nil: true
# field :position, type: Integer, default: 0
validates :user, presence: true, allow_blank: false, allow_nil: false
validates_length_of :notes, :minimum => 2, allow_blank: false
end
然后,当您尝试保存或验证包含错误数据的记录时,您会得到以下结果:
ruby-1.9.2-p290 :028 > QueueItem.validators
=> [#<ActiveModel::Validations::PresenceValidator:0x007f8303adb190 @attributes=[:user], @options={:allow_blank=>false, :allow_nil=>false}>, #<ActiveModel::Validations::LengthValidator:0x007f8303ee5a60 @attributes=[:notes], @options={:minimum=>2, :allow_blank=>false}>]
ruby-1.9.2-p290 :029 > qi = QueueItem.new
=> #<QueueItem _id: 4edf5a0535be359a79000004, _type: nil, created_at: nil, updated_at: nil, user_id: nil, appointment_time: nil, notes: nil, called: false, visited: false, rejected: false>
ruby-1.9.2-p290 :030 > qi.notes = "x"
=> "x"
ruby-1.9.2-p290 :031 > qi.valid?
=> true
似乎验证实际上已在模型中注册,如QueueItem.validations 所示。那么,为什么它们总是返回 true?这不仅发生在这个模型中,而且发生在我的应用程序中的所有模型中。
更新
我添加了一个自定义验证器,并且成功触发。
validate :test_validation
def test_validation
logger.info ":test_validation has fired"
self.errors[:base] << "Something is royally screwed!"
end
现在,当我调用model.valid? 时,它会返回false,并且记录器会输出该消息。自定义验证器实际上是在向对象添加错误,并返回 false。仍然不清楚为什么标准的 ActiveModel 没有被执行。有没有办法追踪这些?
【问题讨论】:
-
奇怪,我真的不知道为什么会这样
标签: ruby-on-rails ruby-on-rails-3 validation mongoid activemodel