Reti
Reti

Reputation: 619

Rails: Getting the most recent datetime in a child model

I have the parent model of user and user has_many :events. From the user view, how can I find the most recent datetime (event.time) of event?

I'm thinking that a find_by will work, but I'm not sure on how to do that.

Upvotes: 1

Views: 1115

Answers (4)

iam
iam

Reputation: 137

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. You should use

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

instead.

Upvotes: 0

Ramanavel
Ramanavel

Reputation: 408

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

like this you can get the event time

Upvotes: 0

Andrey Kuznetsov
Andrey Kuznetsov

Reputation: 11830

user.events.find(:all, :order => 'time desc', :limit => 100) where limit is number of recent events you need or: user.events.find(:first, :order => 'time desc') if you need one most recent event.

Upvotes: 1

Nikita Rybak
Nikita Rybak

Reputation: 68006

Something like this.

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

You can read more here:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001777

Upvotes: 2

Related Questions