如何在Rails中创建“即将到来的生日”模块?(How to create “Upcoming birthdays” module in Rails?)

编程入门 行业动态 更新时间:2024-10-28 19:20:43
如何在Rails中创建“即将到来的生日”模块?(How to create “Upcoming birthdays” module in Rails?)

我有一个表“用户”与列“date_of_birth”(DATE格式与日,月,年)。 在前端,我需要列出5个即将到来的生日。

用了很长时间试图解决逻辑问题......也在Google上浏览了所有可能的文章,但没有运气。

任何建议如何在RoR中做到这一点?

谢谢!

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 work out the logic.. also browsed every possible article in Google with no luck..

Any suggestions how to do this in RoR?

Thanks!

最满意答案

有几个答案建议计算/存储每年的日常数据并对其进行排序,但是如果您接近年底并且需要在明年年初考虑到生日,那么这样做不会有太大的好处。

我会为你计算每个人下一个生日的完整日期(年,月,日)的解决方案,然后对其进行排序。 您可以在Ruby代码中执行此操作,也可以在数据库中使用存储过程。 后者会更快,但会让你的应用更难以在以后迁移到不同的数据库平台。

只需每天更新即将到来的生日的列表即可,这意味着您可以使用某种形式的缓存。 因此,查询/代码所需的速度并不是一个问题,只要你缓存结果就可以正常工作:

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)

编辑 :修正了与闰年正常工作。

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.

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)

Edit: Fixed to work correctly with leap years.

更多推荐

本文发布于:2023-08-04 15:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417534.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   生日   如何在   Rails   module

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!