我知道您的数据库中的start_time
列是字符串类型,并且您希望查找日期以标识上个月或当前月份的特定字符串开头的所有行.
我将首先为这些格式化的日期字符串前缀创建一个范围,如下所示:
date_prefixes = [1.month.ago, 1.month.since].map { |time| time.strftime('%Y-%m') }
#=> ["2023-10", "2023-12"]
prefixes_range = Range.new(*date_prefixes, exclude_end = true)
#=> "2023-10"..."2023-12"
然后,您可以将该范围传递给ActiveRecord
查询,以查找该范围中包含的所有字符串.这将是所有以2023-10
或2023-11
开头的开始日期,但不是以2023-12
开头,因为exclude_end = true
.
Event.where(start_time: prefix_range)
这基本上转换为如下所示的SQL查询:
start_date >= '2023-10' AND start_date < '2023-12'
把所有东西放在一个范围内:
# in app/models/event.rb
scope :started_this_or_previous_month, -> {
where(
start_date: Range.new(
*[1.month.ago, 1.month.since].map { |t| t.strftime('%Y-%m') }, true
)
)
}
# use scope like this:
Event.started_this_or_previous_month.where(rained_out: false)
顺便说一句.即使您使用的gem要求start_date
是一个字符串.您可能希望考虑向表中添加一列,如start_at
或start_on
,类型为DATETIME或DATE,并使这两列保持同步.这将使数据库查询变得更加容易.