Mongoid验证不起作用

时间:2011-07-10 09:46:37

标签: ruby-on-rails ruby-on-rails-3 validation mongodb mongoid

我有一个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”)。

我如何让他们工作?

1 个答案:

答案 0 :(得分:3)

对我而言,您的验证工作正常:

place = Place.create(:headline => nil, :address => nil)
puts place.persisted?  # false
puts place.valid?      # false
puts place.save        # false

createsave方法不会引发异常,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)