[Ruby on Rails] Active Record : find by year day or month on a date field

本文介绍在Ruby on Rails中如何利用SQL的extract函数进行精确的日期查询,包括年、月、日等不同粒度的筛选方法,并针对SQLite数据库提供了特定的strftime解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【Ruby on Rails】

extract 方法

假设你的“日期属性”是一个日期(而不是一个完整的时间戳),那么一个简单的地方会给你“按日期查找”:

Model.where(:date_column => date)

 

You don't want find_by_date_column as that will give at most one result.

For the year, month, and day queries you'd want to use the extract SQL function:

你不想用 find_by_date_column 得到一个结果集。
希望使用sql sql函数的年、月和日来查询:

Model.where('extract(year  from date_column) = ?', desired_year)
Model.where('extract(month from date_column) = ?', desired_month)
Model.where('extract(day   from date_column) = ?', desired_day_of_month)

 

然而,如果你使用SQLite,你不得不浪费时间在strftime,因为它不知道怎么提取:

Model.where("cast(strftime('%Y', date_column) as int) = ?", desired_year)
Model.where("cast(strftime('%m', date_column) as int) = ?", desired_month)
Model.where("cast(strftime('%d', date_column) as int) = ?", desired_day_of_month)

%m 和 %d 格式说明符,在某些情况下将添加0领先,可以混淆平等测试,因此 cast(…as int) 将格式化的 字符串 强制转换为 数字。

 

# 摘自 Stack Overflow

# http://stackoverflow.com/questions/9624601/activerecord-find-by-year-day-or-month-on-a-date-field?answertab=votes#tab-top

 

转载于:https://www.cnblogs.com/gaofly520/p/6875091.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值