Alvin Lau Alvin Lau - 1 year ago 86
Ruby Question

Rails calculate age in months

In my rails app I have different age groups that students classify in based on how many months their age is. I want a way to be able to calculate when a student is approaching the end of an age group (for example 18 months) so that the user is notified. Is there a way to work with months and date comparisons in Rails to accomplish this? All help is appreciated.

Answer Source

Since each age group represents a known number of days after the student's birthdate, you can get what you're looking for by comparing their age (in days) to each particular age group's upper boundary (also in days).

age_groups = [6.months, 12.months, 18.months, 24.months, 36.months]
student_age_in_days = ( - student.birthdate)

group_nearing_end = age_groups.detect do |threshold|
  student_age_in_days.between(threshold - 5.days, threshold)     

if group_nearing_end
  # send notification