2014-09-26 87 views
-2

我想查詢特定日期時間之前創建的記錄。我找不到如何做到這一點的例子。這是一個Rails 4應用程序。如何查找早於特定時間創建的Rails模型?

specific_time = 2.weeks.ago 
Thing.where... # created earlier than specific_time 
+1

'Thing.where(:created_at.lt => specific_time)' - 工作的呢? – 2014-09-26 18:09:53

+2

http://stackoverflow.com/q/7978018/438992和外推。似乎有很多例子,也許谷歌只是更瞭解我。 – 2014-09-26 18:10:14

+0

哈哈,也許吧。我使用的是DuckDuckGo而不是Google。 StackOverflow甚至沒有告訴我有重複。 – Andrew 2014-09-26 18:21:04

回答

1

戴維提到,this answer會做。

如果您想使用純ActiveRecord,我仍然會添加我的2美分。

ancient_time = 100.years.ago 
specific_time = 2.weeks.ago 

Thing.where(created_at: ancient_time..specific_time) 
# => SELECT `things`.* FROM `things` WHERE (`things`.`created_at` BETWEEN '1914-09-26 19:54:28' AND '2014-09-12 18:54:28') 

咩,只是懶惰:)