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.
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:
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)
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)
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)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With