Validations not working?


I’m having some serious problems with my validations. I have a mongoid model set up with validations, which looks like this:

class Apartment

include Mongoid::Document

include Mongoid::Timestamps

validates :price, :numericality => { :greater_than => 0, :allow_blank => false }

field :price, :type => Integer

But then when I actually try to run the validations, they pass and claim the object is valid, even if I pass complete garbage. Here’s the output:

ruby-1.9.2-p180 :006 > Apartment.validators_on(:price)

=> [#<ActiveModel::Validations::NumericalityValidator:0x00000102924cc8 @attributes=[:price], @options={:only_integer=>false, :allow_nil=>false, :greater_than=>0, :allow_blank=>false}>]

ruby-1.9.2-p180 :007 > a = => “G@I$G@GR#&GUGshkj4h53$$$*@^”)

=> #<Apartment _id: 4e1d66f835be35fddb000002, _type: nil, created_at: nil, updated_at: nil, address: nil, price: “G@I$G@GR#&GUGshkj4h53$$$*@^”>

ruby-1.9.2-p180 :008 > a.valid?

=> true

I’ve tried disabling gems, commenting out and then re-adding validations one by one, but nothing seems to work. If you have any fresh direction on how to track this down, I’d really appreciate it. Thanks!



that price looks like random stuff. Is it relevant that you call the validator before the field-definition?



Yes, the price is random junk that’s clearly supposed to fail validation, but it passes with no errors.

I just tried it with the validations after the field definitions; still the same problem.



Hi Avishai,

i just tried this:

irb(main):001:0> “G@I$G@GR#&GUGshkj4h53$$$*@^”.to_i

=> 0

As I don’t know how the conversion would work, but if it works like that it will return 0. But it still should not be valid.Hmmm.


Right, but even so, it should fail. When I try pasting my Apartment model into a fresh Rails app, it does:

ruby-1.9.2-p180 :001 > a = => “G@I$G@GR#&GUGshkj4h53$$$*@^”)

=> #<Apartment _id: 4e1d74fa35be3560e8000001, _type: nil, created_at: nil, updated_at: nil,price: “G@I$G@GR#&GUGshkj4h53$$$*@^”>

ruby-1.9.2-p180 :002 > a.valid?

=> false

I compared the Gemfiles of both apps, and they’re identical… This is very strange…