开发者

Where and how to do custom validation on models?

Lets say we have a simple model that stores two integers, the min and the max. We would like to force min <= max.

class MinMax
  include MongoMapper::Document

  key :min, Integer
  key :max, Integer

  validate_presence_of :min, :m开发者_StackOverflow社区ax
end

1) How would you validate that min is indeed equal or less than max?

2) If you don't think this is the responsibility of the model, then where and who should do that validation?


validates :min_le_max

def min_le_max
  self.min <= self.max
end


I'll answer your questions in reverse. For question 2, validations such as this absolutely are the responsibility of the model. Pretty much anything that is the core logic of your program belongs in your models; controllers are only for mapping from HTTP requests to the appropriate model methods.

For 1, just use validates to call a custom validation method

validates :valid_range

def valid_range
  min <= max
end

If you want a custom error message, add the error message explicitly in the validation:

validate :valid_range

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


The class level method is validate, not validates ...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜