Where and how to perform custom validation on models?

Suppose we have a simple model that stores two integers: min and max. We would like to force min <= max.

class MinMax
  include MongoMapper::Document

  key :min, Integer
  key :max, Integer

  validate_presence_of :min, :max
end

1) How would you confirm that min is really equal to or less than max?

2) If you do not think that this is the responsibility of the model, then where and who should do this check?

+3
source share
3 answers
validates :min_le_max

def min_le_max
  self.min <= self.max
end
+2
source

. 2 , , . , , ; HTTP .

1 validates

validates :valid_range

def valid_range
  min <= max
end

, :

validate :valid_range

def valid_range
  errors.add_to_base("Not a valid range") unless min <= max
end
+2

Class level method validate, not validates...

+1
source

Source: https://habr.com/ru/post/1766020/


All Articles