goddamnyouryan
goddamnyouryan

Reputation: 6896

Ordering by a related classes created_at in Rails

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

Answers (2)

David Barlow
David Barlow

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

Pete
Pete

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

Related Questions