【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