views:

32

answers:

2

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, :max
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?

+1  A: 
validates :min_le_max

def min_le_max
  self.min <= self.max
end
PeterWong
Oh nice, thanks! What if I need to send an error message back to the user to tell what went wrong?
randomguy
inside the method, use `errors.add :field_name, "error message"` or `errors.add_to_base("error message")`
PeterWong
+1  A: 

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
Brian Campbell
Right, thanks bro! What if I needed to send an error message back to the user to tell what went wrong? Ie. how do you plugin the error messages into this?
randomguy