2014-04-04 74 views
8

我试图列出记录最近创建的位置视图或从过去24小时使用activerecord更新的记录,但是我需要一些初学者开发人员的帮助。过去24小时内导轨列表创建/更新记录

有没有人知道在控制器/视图中实现此解决方案?先谢谢您的帮助。

回答

23

由于您使用Rails的,我会假设你有这些文件,对应于位置的资源:

app/views/locations/index.html.erb 
app/controllers/locations_controller.rb 
app/models/location.rb 

有在过去24小时内查询记录数ActiveRecord的选择:

  1. 此示例演示了您可以指定查询时间戳列的范围的概念。

    @locations = Location.where(updated_at: (Time.now - 24.hours)..Time.now) 
    
  2. 正如在下面的评论中指出的,上述查询可能会有一小部分精度错误。您可以存储变量now = Time.now,以确保您的查询跨越24小时。

    now = Time.now 
    @locations = Location.where(updated_at: (now - 24.hours)..now) 
    
  3. 你可以消除减法运算,并让Rails的为您处理它,这也可能会导致轻微的24小时的精确窗口偏移。

    @locations = Location.where(updated_at: 24.hours.ago..Time.now) 
    
  4. 你也可以放弃在where参数哈希语法,传递,与>比较运算过滤SQL字符串。

    @locations = Location.where('updated_at > ?', 24.hours.ago) 
    

在你的控制器中添加一个索引操作,用您的首选查询方法:

def index 
    @locations = Location.where(updated_at: 24.hours.ago..Time.now) 
end 

在您看来,添加这些行:

<table> 
    <thead> 
    <tr> 
     <th>Id</th> 
     <th>Name</th> 
     <th>Created_At</th> 
     <th>Updated_At</th> 
    </tr> 
    </thead> 
    <tbody> 
    <% @locations.each do |location| %> 
     <tr> 
     <td><%= location.id %></td> 
     <td><%= location.name %></td> 
     <td><%= location.created_at %></td> 
     <td><%= location.updated_at %></td> 
     </tr> 
    <% end %> 
    </tbody> 
</table> 
+0

为什么120.day ?问题是否修改? –

+0

不,它不是。那只是另一个随机的例子。我更新了答案,使用'24.hours'与Q协议。感谢您检查! – sealocal

+0

也可以工作:'Location.where(updated_at:1.day.ago..Time.now)' – Adobe

相关问题