开发者

Rails 2.3.5: How to handle this type of validation

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 datab开发者_StackOverflow中文版ase.

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?


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜