在我的rails应用程序中,我有不同的年龄组,学生根据他们的年龄分数来分类。我想要一种能够计算学生何时接近年龄组(例如18个月)以便通知用户的方法。有没有办法在Rails中使用月份和日期比较来实现这一目标?感谢所有帮助。
更新:
这是一种更简单的方法,我想出了如何计算它kid.dob.advance(months: 18)
确定了学生到达年龄组结束的日期。
<% if kid.dob.advance(months: 17) <= Date.today && kid.dob.advance(months: 18) >= Date.today %>
// notification
<% end %>
这意味着用户将在学生到达年龄组结束后的30天内收到通知。数字也可以更改为来自数据库的存储数据,并且可以正常工作。欢呼声。
答案 0 :(得分:0)
由于每个年龄组代表学生生日后的已知天数,您可以通过比较他们的年龄(天数)与每个特定年龄组来获得您正在寻找的内容。上边界(也以天为单位)。
age_groups = [6.months, 12.months, 18.months, 24.months, 36.months]
student_age_in_days = (Date.today - student.birthdate)
group_nearing_end = age_groups.detect do |threshold|
student_age_in_days.between?(threshold - 5.days, threshold)
end
if group_nearing_end
# send notification
end
答案 1 :(得分:0)
这是我的方法:
runtimeArgs
我也看到了这个实现:
def age_in_months(date_of_birth)
return 0 unless date_of_birth
Time.zone.today.month + Time.zone.today.year * 12 - date_of_birth.month - date_of_birth.year * 12
end