如何获取阵列中的最后更新日期?

时间:2015-04-21 17:32:20

标签: ruby-on-rails ruby arrays date

此代码仅显示数组model.request_reports

内的值
  1. 为了获得最新信息,我必须循环并比较当前的情况 最后一次保存report.updated_at的{​​{1}}。有一件事要找 out是report.update_at value字段的类,以及如何将它们相互比较。该课程为update_at

  2. 我需要跟踪具有最新ActiveSupport::TimeZone的报告的数组索引作为循环,以便我可以在循环后访问它。

  3. 问题是,我不知道该怎么做:

    updated_at

3 个答案:

答案 0 :(得分:0)

添加到@meagar评论。您应该使用DB对表进行排序。

据说我们需要知道你正在使用什么数据库,因为确切的命令各有不同。

Mongo w / Mongoid将是Model.order_by(:updated_at => 'desc').first

答案 1 :(得分:0)

我的循环必须通过数组并检查最大日期值,因为在我使用的系统中,它会自动按字段排序报告数组" due_at"这不是报告最近更新的记录。下面的代码对我有用。

msg = ""

reports_arr = model.request_reports
last_modified_report = model.last_modified_report

recent = nil
recent_report = nil

reports_arr.each_with_index do |report,index|
updated_at = report.updated_at
if index == 0 
recent = updated_at
recent_report = report
end

if updated_at > recent
recent = updated_at
recent_report = report
end

last_modified_report = recent_report

end



msg = msg + "#{recent}---"
msg = msg + "#{recent_report}---"
msg = msg + "#{last_modified_report}"

model.last_modified_report = last_modified_report
model.save(validate: false)


msg

答案 2 :(得分:0)

如果您绝对无法直接在数据库中查询所需信息,那么OP的答案才会有用。我假设您只想要索引,以便找到最新的索引?

即使自动排序在一列上,您对数据的查询也可以将其排序在不同的列上。

model.request_reports.order_by(:updated_at => 'desc').first

如果您的默认作用域弄乱了您的查询,您可以要求一个未列表的列表,但我怀疑默认排序会导致任何问题。

model.unscoped.order_by(:updated_at => 'desc').first

您可以将已经编写的查询串在一起:即使request_reports是您拥有的查询或范围,这也很有用。

这比获取所有内容和循环更便宜 - 如果可以的话,你最好找到一种方法来获取db查询中所需的信息。

相关问题