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?
self.posts.lastbeingnil?