ruby-on-rails - 如何仅根据日期和月份获取用户的生日

标签 ruby-on-rails postgresql date

我想要一个今天生日和即将到来的生日(明天)的成员列表。

In users.controller.rb
def birthday
   @birthday_users = User.all.order("created_at DESC").where(:birthday => Date.today)
end

def upcoming_birthday
   @upcoming_birthday_user = User.all.order("created_at DESC").where(:birthday => 1.days.from_now )
end

这些代码仅在日、月、年与今天相同时才有效。

例子:

用户 1 的生日 = 2018 年 10 月 3 日(显示在生日列表中)

用户 2 的生日 = 2000 年 10 月 3 日(未显示在生日列表中)

最佳答案

在用户模型中

PostgreSQL

scope :today_birthday, { where('EXTRACT(month FROM birthday) = ? AND EXTRACT(day FROM birthday) = ?', Date.today.month, Date.today.day).order("created_at DESC") }

scope :upcoming_birthday, { where('EXTRACT(month FROM birthday) = ? AND EXTRACT(day FROM birthday) = ?', 1.days.from_now.month, 1.days.from_now.day).order("created_at DESC") }

MySql

scope :today_birthday, { where('MONTH(birthday) = ? AND DAY(birthday) = ?', Date.today.month, Date.today.day).order("created_at DESC") }

scope :upcoming_birthday, { where('MONTH(birthday) = ? AND DAY(birthday) = ?', 1.days.from_now.month, 1.days.from_now.day).order("created_at DESC") }

关于ruby-on-rails - 如何仅根据日期和月份获取用户的生日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52619569/

相关文章:

php - 将 MySQL 日期时间转换为非常特定的格式以进行导出

mysql - ORDER BY 格式错误的日期列

ruby-on-rails - I18n 数组中的插值

ruby-on-rails - 卡住关联对象

关于时区的 PostgreSQL 提取函数

python - 处理 Django/Postgres 自然外键级联更新

Postgresql 使用时区 UTC 创建表字段名时间戳

mysql - Thinking Sphinx 和 rails : Lost connection to MySQL server at 'reading initial communication packet' error

ruby-on-rails - 在 Rails 迁移中将一列更新为另一列的值

sql-server - 区域日期格式和数据库日期格式的不同日期格式的 SQL Server 错误