如何仅基于日期和月份获取用户的生日

时间:2018-10-03 04:08:40

标签: 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日(未显示在生日列表上)

2 个答案:

答案 0 :(得分:1)

在用户模型中

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") }

答案 1 :(得分:0)

我假设您想查找今天有生日的所有用户。因此,您可能想忽略年份,而在查询时只考虑月份和日期。下面的代码可能会帮助您:

def birthday
  @birthday_users = User.where('EXTRACT(month FROM birthday) = ? AND EXTRACT(day FROM birthday) = ?', Date.today.strftime("%m"), Date.today.strftime("%d"))
end

def upcoming_birthday
  tomorrow = Date.today + 1.day
  @upcoming_birthday_users = User.where('EXTRACT(month FROM birthday) = ? AND EXTRACT(day FROM birthday) = ?', tomorrow.strftime("%m"), tomorrow.strftime("%d"))
end