2017-08-07 68 views
0

我正在使用Rails 5和PostgreSQL 9.5。我有一张表格,内容如下。Rails finder方法找到一个超过24小时的实体?

cindex=# \d crypto_index_values; 
            Table "public.crypto_index_values" 
    Column |   Type    |       Modifiers 
------------+-----------------------------+------------------------------------------------------------------ 
id   | integer      | not null default nextval('crypto_index_values_id_seq'::regclass) 
value  | double precision   | 
index_date | timestamp without time zone | not null 
created_at | timestamp without time zone | not null 
updated_at | timestamp without time zone | not null 

鉴于时间点(说“2017年7月29日11:10”)存储在变量“my_date”,如何将我写一个Rails Finder查询返回单个Rails的条目返回最小的“index_date”与“my_date”距离至少24小时?所以,如果我有这个表中的数据

14 | 133.951211424387 | 2017-07-31 19:10:03.235566 | 2017-07-29 19:10:03.267727 | 2017-07-31 19:10:03.267727 
15 | 133.951211424387 | 2017-07-31 19:20:03.59569 | 2017-07-28 19:20:03.629418 | 2017-07-31 19:20:03.629418 
16 | 139.104155235946 | 2017-07-31 19:30:08.037045 | 2017-07-31 19:30:08.04715 | 2017-07-31 19:30:08.04715 

并给予我的例子,我希望查询到ID为“15”返回行,因为ID为“14”的行不是从我的实例24个小时的路程。通常这种查询将工作

CryptoIndexValue.where('index_date = ?', my_date - 1) 

但由于没有一个条目完全24小时外,它没有。

回答

0

我不认为你的例子值相当的工作 - 至少我不知道你会怎么选择从与该索引日期表值,减去一天。你的意思是“最早的日期从my_date起至少还有一天”?

CryptoIndexValue. 
    where('index_date > ?', my_date + 1.days). 
    order(:my_date, :id). 
    take 

我的情况下,你需要在具有相同index_date两行的抢七,但将其删除,如果是由于约束是不可能添加:id到订单。但是,也许你的意思是减去一天而不是加入。

+0

好,我的例子不好。我编辑了我的问题,用“7-28”代替“7-30”。 – Dave

0

您应该使用>算子结合order

CryptoIndexValue.order(:index_date).find_by('index_date > ?', DateTime.now - 24.hours)

+1

可能更适合按'index_date'而不是'id'进行排序。 – alexanderbird

+1

而且你还需要从'my_date'减去24小时# – alexanderbird