开发者

Mongoid validations not working

开发者 https://www.devze.com 2023-03-18 23:36 出处:网络
I have a Mongoid model, and the validations aren\'t working, at all. No error message开发者_C百科s, no problems, but I can insert invalid data.

I have a Mongoid model, and the validations aren't working, at all. No error message开发者_C百科s, no problems, but I can insert invalid data.

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

Even though it looks like it's supposed to work, the model saves without throwing an error (value nil or "abc", for example).

How do I get them to work?


For me your validations are working correctly:

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

The create and save methods do not raise an exception, save returns false if unsuccessful (fails validation). The save! method does raise the following exception:

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

精彩评论

暂无评论...
验证码 换一张
取 消