Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails list created/updated records within last 24 hours

I'm trying to list records for a locations view of recently created at or updated records from the last 24 hours using activerecord but am a beginner developer needing some help.

Does anyone know a solution for implementing this in the controller/view? Thanks in advance for the help.

like image 767
Justin Seidl Avatar asked Apr 04 '14 00:04

Justin Seidl


1 Answers

Since you're using Rails, I will assume that you have these files, corresponding to a Locations resource:

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

There are a few ActiveRecord alternatives for querying records in the past 24 hours:

  1. This example demonstrates the concept that you can specify a range for querying the timestamp columns.

    @locations = Location.where(updated_at: (Time.now - 24.hours)..Time.now)
    
  2. As pointed out in the comments below, there may be a fraction of a second precision error with the above query. You can store a variable, now = Time.now, to ensure that your query spans exactly 24 hours.

    now = Time.now
    @locations = Location.where(updated_at: (now - 24.hours)..now)
    
  3. You could eliminate the subtraction operation and let Rails handle it for you, which may also result in a slight offset from an exact window of 24 hours.

    @locations = Location.where(updated_at: 24.hours.ago..Time.now)
    
  4. You can also forego the hash syntax in the where parameters, passing a SQL string that filters with the > comparison operator.

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

In your controller, add an index action, with your preferred query approach:

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

In your view, add these lines:

<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>
like image 85
sealocal Avatar answered Oct 13 '22 03:10

sealocal