0

I have am serving up a bunch of objects into a status feed and want to sort them based off their latest activity. If I were just sorting off of the created_at attribute of each object I would use the code:

    articles = Article.all
    documents = Document.all
    @feeds = (articles + documents).sort! { |b, a| a.created_at <=> b.created_at }

But let's say that people can post in documents such that the latest activity in a document is the created_at attribute in the latest post. Then I would like to sort as such:

 @feeds = (articles + documents).sort! { |b, a| a.latest_activity <=> b.latest_activity }

And I would define latest_activity in the models:

In Document.rb

 def latest_activity
      self.posts.last.created_at
 end

in Article.rb

 def latest_activity
     self.created_at
 end

This doesn't work.. the local server serves the following error:

 undefined method `created_at' for nil:NilClass

How can I accomplish the sorting desired here?

4
  • 1
    Shot in the dark-- Documents with no posts results in self.posts.last being nil? Commented Sep 12, 2011 at 19:58
  • self.posts.last.try(:created_at) Commented Sep 12, 2011 at 20:37
  • hmmmm Platinum Azure, good job - totally forgot to add a check for documents with no posts!!! Commented Sep 13, 2011 at 16:04
  • if you want to write it as an answer, i'll check-mark it. Commented Sep 13, 2011 at 16:05

1 Answer 1

1

I would normally use the "updated_at" rather than created_at. Then, in your Post class:

class Post < ActiveRecord::Base
  belongs_to :document, :touch => true
end

This means that when a post is saved, it will update the document's updated_at column.

Then, to simplify:

articles = Article.all
documents = Document.all
@feeds = (articles + documents).sort_by(&:updated_at)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.