Getting most active has many models
I have a scenario where a person 开发者_StackOverflowcould have done multiple activities on the site. So my person activity looks like following:
class User < ActiveRecord::Base
has_many :activities
and similarly activity model
class Activity < ActiveRecord::Base
belongs_to :user
Now i want to find the users and their activities in the order of their recent activity of the site..
For example if User A has done Activites A and B today and User B has done Activity C about a week ago, then user A should be listed above User B.
This can be done by writing SQL query but i am not sure if their is a good railish way to do this thing.
Thanks in Advance !!
I don't think there is a rails way. If you're using Rails 3 you could try this:
Activity.order('created_at DESC')
If you're using Rails 2 you could do it like Sam said in the comment above
Activity.all(:order => 'created_at DESC')
and for example if you want only the last 10 activities or only the activities since yesterday, you could do this
Activity.order('created_at DESC').limit(10)
Activity.where('created_at >= ?', Date.yesterday.midnight).order('created_at DESC')
精彩评论