2017-08-07 66 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