How to create “Upcoming birthdays” module in Rails?

后端 未结 9 2254
栀梦
栀梦 2020-12-29 17:46

I have a table \"users\" with a column \"date_of_birth\" (DATE format with day, month, year). In frontend I need to list 5 upcoming birthdays.

Spent ages trying to w

9条回答
  •  无人及你
    2020-12-29 18:18

    If your database is mysql, the following is probably faster:

    scope :birthday_next_week, (lambda {
      where('DayOfYear(date_of_birth) >= 7
         And DayOfYear(date_of_birth) - DayOfYear(curdate()) Between 0 and 6) Or
       (MOD(YEAR(curDate()),4) = 0) And MOD(YEAR(curDate()),100) != 0
        And (DayOfYear(date_of_birth) + 366 - DayOfYear(curdate())) % 366 < 7) Or
         (DayOfYear(date_of_birth) + 365 - DayOfYear(curdate())) % 365 < 7').
        order('DATE_FORMAT( date_of_birth, "%m-%d" ) ASC')
    })
    

    Edit: changed to make it work in the week before new years eve / leap years.

提交回复
热议问题