2

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?

1
  • Are you getting a validation error with this rule or maybe some other error? The api docs show validating an age field, no mention there of needed any conversions. Commented Apr 21, 2010 at 18:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.