Reputation: 6896
I've got a model User with a related class (User has_many Posts, Post belongs_to User). I want to display Users in a list, with those who have posted most recently at the top. So basically I want to order the List of Users by the created_at date of their last post. How is the best way to query this in Rails 3?
Thanks!
Upvotes: 1
Views: 98
Reputation: 4974
Maybe try something like this.
class User < ActiveRecord::Base
has_many :posts
has_one :last_post, :order => 'created_at DESC', :class_name => "Post"
scope :sort_by_last_post_desc, :include => :last_post, :order => ('posts.created_at DESC')
end
NOTE: not tested
Upvotes: 1
Reputation: 1482
I think I would just do this by pulling the Posts, ordering by created_at and doing a group by on the user_id.
Upvotes: 2