views:

194

answers:

1

Hello, i have a set of select inputs representing a users birthday: birthyear, birthmonth and birthday. And 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. But 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? or is there any easier way to check the users age?

Thanks, Micke

+1  A: 

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.

Tony Fontenot
God, you where right, rails converts it to integer if it is in the db, just switched and tested. Thank you! i feel so stupid.
Micke
No need to feel stupid. Rails does a *lot* behind the scenes and it is easy to get lost when something doesn't work as you expected.
Tony Fontenot
It really does, and it is great but you tend to think you have to do it yourself so you make the easy things to do really hard. I think that is a curse from comming from PHP
Micke