[英]Rails: Getting the most recent datetime in a child model
I have the parent model of user
and user
has_many :events
. 我有
user
和user
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.