ruby-on-rails-3 - Rails 列出过去 24 小时内创建/更新的记录

标签 ruby-on-rails-3 list activerecord

我正在尝试使用 activerecord 列出最近在过去 24 小时内创建或更新的记录的位置 View 的记录,但我是需要帮助的初学者开发人员。

有谁知道在 Controller / View 中实现这个的解决方案?在此先感谢您的帮助。

最佳答案

由于您使用的是 Rails,我假设您有这些文件,对应于 Locations 资源:

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

查询过去 24 小时内的记录有几个 ActiveRecord 替代方案:
  • 此示例演示了您可以指定查询时间戳列的范围的概念。
    @locations = Location.where(updated_at: (Time.now - 24.hours)..Time.now)
    
  • 正如下面评论中所指出的,上述查询可能存在几分之一秒的精度误差。您可以存储一个变量 now = Time.now ,以确保您的查询准确跨越 24 小时。
    now = Time.now
    @locations = Location.where(updated_at: (now - 24.hours)..now)
    
  • 您可以消除减法运算并让 Rails 为您处理,这也可能导致与 24 小时的精确窗口略有偏移。
    @locations = Location.where(updated_at: 24.hours.ago..Time.now)
    
  • 您也可以放弃 where 中的哈希语法。参数,传递一个使用 > 过滤的 SQL 字符串比较运算符。
    @locations = Location.where('updated_at > ?', 24.hours.ago)
    

  • 在您的 Controller 中,使用您喜欢的查询方法添加一个索引操作:
    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>
    

    关于ruby-on-rails-3 - Rails 列出过去 24 小时内创建/更新的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22851676/

    相关文章:

    ruby-on-rails - 如何在邮件模板中生成正确的 URL?

    ruby-on-rails - rails : Using CanCan to assign multiple roles to Users for each organization they belong to?

    python - 列表理解分配/比较在 256 之后失败

    ruby-on-rails - Rails 3.1 限制用户创建的对象

    ruby-on-rails - Rails 控制台和 mongodb

    ruby - 如何在 Ruby on rails 中访问 Controller 中的 hidden_​​field

    java - 从 Java 中的列表打印模式

    java - 与另一个列表相比更新列表元素的快速方法

    sql - 查找字段值全部为 LOWERCASE 的记录

    ruby-on-rails - Rails 委托(delegate)设置值