jay
jay

Reputation: 12495

use custom methods for sorting in rails .sort!

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?

Upvotes: 0

Views: 1236

Answers (1)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

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)

Upvotes: 1

Related Questions