我有一个Mongoid模型,验证根本不起作用。没有错误消息,没有问题,但我可以插入无效数据。
class Place
include Mongoid::Document
include Mongoid::Timestamps
field :address, :type => String, :required => true
field :headline, :type => String, :required => true
validates :headline, :presence => true, :length => { :minimum => 10, :allow_blank => false }
validates :address, :presence => true, :length => { :minimum => 5, :allow_blank => false }
# ...
end
即使看起来它应该有效,但模型会保存而不会抛出错误(例如,值为nil或“abc”)。
我如何让他们工作?
答案 0 :(得分:3)
对我而言,您的验证工作正常:
place = Place.create(:headline => nil, :address => nil)
puts place.persisted? # false
puts place.valid? # false
puts place.save # false
create
和save
方法不会引发异常,save
如果不成功则返回false(验证失败)。 save!
方法确实引发了以下异常:
Validation failed - Headline can't be blank, Headline is too short (minimum is 10 characters), Address can't be blank, Address is too short (minimum is 5 characters). (Mongoid::Errors::Validations)