Search code examples
ruby-on-railsruby-on-rails-3validationmongoidactivemodel

Rails3/Mongoid Validations Not Running


In my application, it seems that no ActiveModel validations are running, at all. That is, they always return true (valid) no matter how invalid the data actually is.

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

Then, when you try to save or validate a record with bad data, this is what you get:

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 

It seems that the validations are in fact being registered in the model, as shown by QueueItem.validations. Why, then, do they always return true? This is happening not just in this model, but in all models in my application.

UPDATE

I added a custom validator, and that is successfully firing.

validate :test_validation

def test_validation
  logger.info ":test_validation has fired"
  self.errors[:base] << "Something is royally screwed!"
end

Now, when I call model.valid?, it returns false, and the logger outputs that message. The custom validator is in fact adding errors to the object, and returning false. Still not clear why the standard ActiveModel ones are not being executed. Is there any way to trace these?


Solution

  • So, turns out that there was a corrupted string in the locals/en.yml file under the errors: section.