0

I would like to implement warning errors on model validation with Ruby mongoid gem.

I kinda followed this example found here Efficient way to report record validation warnings as well as errors?

class MyModel

validate :check_warnings

def warnings
  @warnings ||= ActiveModel::Errors.new(self)
end

def check_warnings
  warnings.add(:some_field, :not_exist) if some_field.blank?
  warnings.add(:another_field, :not_exist) if another_field.blank?
end
end

When warnings value is acessed in Rails helper to display warnings, it is empty.

p doc.warnings.size => 0

But if I force a validation error

def check_warnings
  warnings.add(:some_field, :not_exist) if some_field.blank?
  warnings.add(:another_field, :not_exist) if another_field.blank?

  errors.add(:yet_another_field, :not_exist) if yet_another_field.blank?
end

# in helper
p doc.errors.size => 1
p doc.warnings.size => 2

warning errors are preserved.

Is this maybe a mongoid bug or am I missing something.

by
TheR

TheR
  • 63
  • 1
  • 6

1 Answers1

0

You need to perform the validation (by calling validate, valid?, save/save! etc.) before looking at the errors or your warnings. If you simply look at errors or warnings without having validated you will have empty sets.

D. SM
  • 13,584
  • 3
  • 12
  • 21