2016-07-31 206 views
1

在我的Rails應用程序中,我有不同年齡組,學生根據他們的年齡有幾個月分類。我想要一種能夠計算學生接近年齡組結束時(例如18個月)以便通知用戶的方式。有沒有一種方法可以在Rails中進行月份和日期比較來實現這一點?所有的幫助表示讚賞。Rails按月計算年齡

UPDATE:

這我想通了,如何計算呢kid.dob.advance(months: 18)一個更簡單的方法來確定當學生將達到年齡組的結束日期。

<% if kid.dob.advance(months: 17) <= Date.today && kid.dob.advance(months: 18) >= Date.today %> 

    // notification 

<% end %> 

這意味着用戶將在學生到達年齡組結束後的30天內通知。數字可以更改爲存儲在數據庫中的數據,也可以工作。乾杯。

回答

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 
0

這裏是我的方式做到這一點:

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 

我也看到了這個實現:

def age_in_months(date_of_birth) 
    date_of_birth ? ((Time.zone.today - date_of_birth)/30.437).to_i : 0 
end