我正在尝试使用 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)
@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/