views:

20

answers:

3

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.

+1  A: 

Something like this.

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

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

Nikita Rybak
For some reason, when find returns the results, it is in a weird format. Here's an example: `#<Event:0xb6a26708>` What's going on?
Reti
the result returned is an Event instance. Try _result.time_
Nikita Rybak
I'm not sure what you mean when you say `result.time`. How do I use that?
Reti
user.events.find(:first, :order => "time DESC").time
Nikita Rybak
Thanks, that worked perfectly. And I did have that, but I was having trouble when user didn't have any events. I added an exception and it worked. :)
Reti
+1  A: 

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.

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

like this you can get the event time

Ramanavel