0
在我的應用程序中,似乎根本沒有運行ActiveModel驗證。也就是說,無論數據實際上有多麼無效,它們總是返回true(有效)。Rails3/Mongoid驗證未運行
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
顯示。那麼,爲什麼他們總是迴歸真實?這不僅發生在這個模型中,而且發生在我的應用程序中的所有模型中。
UPDATE
我加了一個自定義的驗證,並已成功發射。
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沒有被執行。有什麼方法可以追蹤這些嗎?
奇怪,我不知道爲什麼會發生這種情況 –