简体   繁体   English

Rails:获取子模型中的最新日期时间

[英]Rails: Getting the most recent datetime in a child model

I have the parent model of user and user has_many :events . 我有useruser has_many :events的父模型。 From the user view, how can I find the most recent datetime ( event.time ) of event ? user角度,我如何找到event 最新日期时间( event.time )?

I'm thinking that a find_by will work, but I'm not sure on how to do that. 我以为find_by可以工作,但是我不确定如何做到这一点。

Something like this. 这样的事情。

user.events.find(:first, :order => "time DESC")

You can read more here: 你可以在这里阅读更多:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001777 http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001777

user.events.find(:all, :order => 'time desc', :limit => 100)其中limit是您需要的最近事件数,或: user.events.find(:first, :order => 'time desc')如果您需要一个最新事件。

Just in case anyone stumbles upon this, the find first helper: 以防万一有人偶然发现此问题,请寻找第一位助手:

user.events.find(:first, :order => 'time desc').time

is now deprecated and removed as of Rails 3.2. 从Rails 3.2开始,现已弃用并删除了它。 You should use 你应该用

user.events.order("time desc").first.try(:time)

instead. 代替。

user.events.find(:first, :order => 'time desc').time

这样你可以得到活动时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM