2017-08-08 31 views
-1

我正在使用Rails 5和PostGres 9.5。我想在我的模型中搜索过去至少一年的条目,然后返回至少一年前的最新条目。如果没有这样的条目,我不想返回任何结果。我在我的模型创造了这个...如何编写一个至少返回一年的查找方法,但是如果没有这样的入口,那么该怎么办?

def self.year_change(from_date) 
    CryptoIndexValue. 
      where('index_date > ?', from_date - 1.years). 
      order(:index_date). 
      take 
    end 

,但是当我把这个跟今天的日期,我得到一个结果......

id | value |   index_date   |   created_at   |   updated_at 
----+-------+----------------------------+----------------------------+---------------------------- 
    2 |  0 | 2017-07-30 15:51:52.118646 | 2017-07-30 15:51:52.147113 | 2017-07-30 15:51:52.147113 

注意“index_date”在返回的是刚刚几天之前。我如何调整我的finder方法,使其只返回至少一年的条目,否则不返回任何结果?

+2

但是'index_date' *为*比一年前更大的...也许你不想'是上述index_date's一年前。这是一个暗示。 –

+0

我被困在我的脑海里,我无法看到你在说什么。我在上面看到索引日期为“2017-07-30 15:51:52.118646”。这似乎在一年内给我。你指的是什么? – Dave

+0

...正在'2017-07-30> 2016-08-08'? –

回答

0

我觉得对现在应该解决的问题留下一个答案是“不道德的”,因此您不应该将其标记为正确的答案。但如果你还没有解决它已经:

2016年是于2017年小,为此所有超过1年于一切造就了今天小:

Date.today - 2.years < Date.today 
=> true 

你的代码目前规定的日期项目被创建为大于-1.years,它不会返回任何内容,因为它是错误的。

因此改变:

where('index_date > ?', from_date - 1.years). 

要:

where('index_date < ?', from_date - 1.years). 
相关问题