2 associations to same table

If I understand correctly, this might work for you:

class User
  has_many :forum_messages
  has_one :most_recent_forum_message, :class_name => 'ForumMessage', :order => 'created_at desc'
  has_one :first_forum_message, :class_name => 'ForumMessage', :order => 'created_at'

then you would use it this way:

u = User.find(:first)
u.most_recent_forum_message.subject (or whatever)
u.first_forum_message.created_at (or whatever)

Disclaimer: I've never used this code. I actually used AWDWR 2 page 334 as a basis and made some changes as necessary. It *should* work, though.


I think I see what you're wanting to do. On a particular forum, you want to display the poster's first message (date or something) and most recent message (date or something) *for every topic*. My advice is to use something like a counter cache column. For each user, store either the dates of the first and most recent post or store the ids so you can easily get to them. With every post the user makes, update the cache column. If you try to find that information dynamically, you're going to have continually slower and slower performance as your topic count increases.


Luca, it looks like ActiveRecord#find_by_sql will let you access

Here's a short excerpt from the doc:

"If you call a complicated SQL query which spans multiple tables the
columns specified by the SELECT will be attributes of the model,
whether or not they are columns of the corresponding table."

Isn't Rails great? :slight_smile:

Obviously, it would be desirable to not use SQL for this, but you have
performance problems. I would advise against doing your own caching of
the latest and oldest post until you find you have no choice. It's
more Rails-y, but it's also more code to go wrong.