[Sdruby] Polymorphic Associations or Method in Model?

Hugh Bien bienhd at gmail.com
Tue Apr 17 08:14:26 GMT 2007


Hi guys,

For an app I'm working on, there's going to be an overview like
Basecamp's that shows all recent events.  So there's a Comment model
and a Note model and I wanted to display both of them in a list
ordered by when they were created.

class User < AR::Base
  has_many :comments, :limit => 10
  has_many :notes, :limit => 10

  def recent_events
    (comments + notes).sort_by(&:created_at)
  end
end

The method 'recent_events' gives me what I want, an array of comments
and notes.  I've been feeling guilty about this though, since it's
loading records into memory and using Ruby to sort them.

I was looking at polymoprhic associations, but wasn't really sure that
this was the right place to use it.  I know polymorphic associations
can handle the case where:

class A belongs to B
class A belongs to C

but I wasn't sure if it could handle

class A has_many B and C

What do you guys think?

- Hugh


More information about the Sdruby mailing list