views:

75

answers:

1

The use case is simple.

I allow users to enter in an expiration field which needs to be between 1 and 15 into a form. The model takes that number and converts it into a datetime (such as adding 15 days from today) and stores it in the database.

What's the correct way to actually validate that though? Do I validate against the datetime format that gets persisted in the database or the select box (1..15) that the user gets to pick through the form? I want to be able to validate that the user is putting in 1..15.. How is this done with ActiveRecord validation in Rails 2.3.5?

Should I just create an attr_accessor for the integer based expiration field and validate against that? What's the clean way of doing this?

+4  A: 

I imagine you have code like this

attr_accessor :expiration_num
before_save :convert_date

def convert_date
  self.expiration = self.expitration_num.days.since
end

So just add a validation method like so:

validate :expiration_correctness

def expiration_correctness
  errors.add_to_base("Must be in 1-15") unless (1..15).include? self.expiration_num
end
Jakub Hampl
+1 for nice answer.
Salil
You could had just used validates_inclusion_of instead of expiration_correctness; convert_date should check if expiration_num is blank.
vise