Rails - 在where查询中检查一个日期是否属于某个月份

Rails - Check if a date belongs to a certain month in where query

使用 Rails 6.

我有一个 ElectricityUsage 模型,带有日期字段 date。我只想提取当月 amount 的所有值。我将如何做到这一点?

我立即尝试的是:

ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat).where(date.month: Date.today.month)

但这显然是行不通的,而且它甚至不能解释年份。我的数据库是 PostgreSQL 上的 运行,如果这有所不同的话。

您可以将 whereDate.current.all_month 一起使用,这基本上只是转换为使用 BETWEEN 的查询,其中开始日期是该月的第一天,结束日期是最后一个:

ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat, date: Date.current.all_month)

这应该适合你

ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat).where("EXTRACT(MONTH FROM date) = ?", Date.current.month)

PostgreSQL Date/Time Functions and Operators

可能是延迟回复,但您可以使用 date_queries gem

model ElectricityUsage < ActiveRecord::Base
  date_queries_for :date
end

然后你可以简单地使用ElectricityUsage.dates_in_this_month找到当月所有错误的记录