Convert input to integer before save in rails
I have a set of select inputs representing a users birthday: birthyear, birthmonth and birthday. I want to validate birthyear like this:
validates_inclusion_of :birthyear, :in =>开发者_开发百科; Date.today.year-50..Date.today.year-12
So the user can be at least 12 years but at most 50 years when they are registering.
My problem is that the variable from the input is a string and not an integer.
So how can I convert the input to an integer? Is there any easier way to check the users age?
Sounds like you have defined the birthyear
db column as a string. Rails will convert the inut params to the appropriate type when assigned. So user.new(params[:user])
will save birthyear
in the type defined buy the db column type.
If you can't change the db column to an integer then try creating an array of the valid strings.
validates_inclusion_of :birthyear,
:in => (Date.today.year-50..Date.today.year-12).map(&:to_s)
Now, bare in mind, in production, the model classes could get cached and you could have a case of the date range being wrong for the new year until you restart.
I would add this in the validate function and not use the inclusion validation to prevent this case.
def validate
current_year = Date.today.year
if birthyear && (birthyear.to_i <= current_year - 50 || birthyear.to_i >= current_year - 12)
errors.add(:birthyear, "must be between 12 and 50 years of age")
end
end
Now, all of this assumes that the input coming in is a 4 digit year.
精彩评论