本文介绍了如何创建“即将到来的生日" Rails中的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表"users",其列为"date_of_birth"(带日,月,年的DATE格式).在前端,我需要列出5个即将到来的生日.

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.

花了很长时间试图弄清楚逻辑..也没有运气就浏览了Google中的所有文章.

Spent ages trying to work out the logic.. also browsed every possible article in Google with no luck..

有人建议如何在RoR中执行此操作吗?

Any suggestions how to do this in RoR?

谢谢!

推荐答案

有几个答案建议计算/存储一年中的某天并对其进行排序,但是仅当您这样做时,这样做并没有多大用处快到年底了,需要考虑在明年年初有生日的人.

Several answers have suggested calculating/storing day of year and sorting on that, but this alone won't do much good when you're close to the end of the year and need to consider people with birthdays in the beginning of the next year.

我将寻求一种解决方案,其中您计算每个人的下个生日的完整日期(年,月,日),然后进行排序.您可以使用Ruby代码或在数据库中使用存储过程来执行此操作.后者会更快,但会使您的应用以后很难迁移到其他数据库平台.

I'd go for a solution where you calculate the full date (year, month, day) of each person's next birthday, then sort on that. You can do this in Ruby code, or using a stored procedure in the database. The latter will be faster, but will make your app harder to migrate to a different db platform later.

每天只更新一次即将到来的生日列表是合理的,这意味着您可以使用某种形式的缓存.因此,所需查询/代码的速度不再是问题,只要您缓存结果,类似这样的命令就可以正常工作:

It would be reasonable to update this list of upcoming birthdays once per day only, which means you can use some form of caching. Thus the speed of the query/code needed is less of an issue, and something like this should work fine as long as you cache the result:

class User
  def next_birthday
    year = Date.today.year
    mmdd = date_of_birth.strftime('%m%d')
    year += 1 if mmdd < Date.today.strftime('%m%d')
    mmdd = '0301' if mmdd == '0229' && !Date.parse("#{year}0101").leap?
    return Date.parse("#{year}#{mmdd}")
  end
end

users = User.find(:all, :select => 'id, date_of_birth').sort_by(&:next_birthday).first(5)

编辑:已修复,可以在leap年内正常使用.

Edit: Fixed to work correctly with leap years.

这篇关于如何创建“即将到来的生日" Rails中的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:48