如何查询过去几周创建的记录? ......从现在到2周前

时间:2012-01-05 01:00:29

标签: ruby-on-rails activerecord

查看此查询有什么问题?

time_range = (Time.now..2.weeks.ago)
access_code = group.group_access_codes.where(:group_access_codes => {:uuid => code, :created_at => time_range}).first

它没有返回有效记录?这是生成的SQL:

SELECT "group_access_codes".* 
FROM "group_access_codes" 
WHERE "group_access_codes"."uuid" = 'ae342d4a13' 
    AND ("group_access_codes".group_id = 391)
    AND ("group_access_codes"."created_at" BETWEEN '2012-01-05 00:53:34.811469' AND '2011-12-22 00:53:34.811521') 

它应该找到的记录:

created_at = 2012-01-05 00:36:41.710613

由于

1 个答案:

答案 0 :(得分:4)

只需翻转你的时间范围就可以了。

time_range = (2.weeks.ago..Time.now)
access_code = group.group_access_codes.where(:group_access_codes => {:uuid => code, :created_at => time_range}).first