How to create “Upcoming birthdays” module in Rails?

后端 未结 9 2235
栀梦
栀梦 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:11

    I too thought that day of year would be the way to go, but the fact that it is different for most of the year depending on whether it is a leap year or not makes it tricky.

    Better is to store the month and day as a string: d.strftime('%m%d'). You can then use that as (possibly) two queries (assuming new column is 'monthday')

    First,

    User.find(:all,
              :condition => [:monthday > Date.now.strftime('%m%d')],
              :select => "DISTINCT monthday",
              :limit => 5)
    

    If you don't get 5 results, do the query again, except use "0101" instead of the date calculation and lower the limit.

    This gets you a list of monthday strings that you then have to turn back into dates.

    If you want users, remove the :select line.

提交回复
热议问题