views:

50

answers:

2

Suppose that model X has_many Ys and model Y belongs_to X. Each Y has a date when it has been inserted to the database. Now, is it possible to load all Xs and eager load last Y for each of X (only the last because each X has bazzilions of Ys)?

+2  A: 

Yes,

Lets take this example

class Song < ActiveRecord::Base
   has_many :votes
end

class Vote < ActiveRecord::Base
  belongs_to :song
end

Add a new association to the Song:

has_one :last_vote, :class_name => 'Vote', :order => 'created_at DESC'

this new association will always return the most recently created Vote for a Song.

To eager load it:

songs = Song.find(:all, :conditions => 'artist_name = "frank"', :include => :last_vote)
Tilendor
It would be interesting to see the join generated by that query. :) It'll probably be best to denormalize a bit and add a field to Song, last_vote_id, updated everytime a new vote is added. Just :include => :last_vote afterwards, no superfluous data loads (or GROUP BY, if smart) needed.
vladr
True, my above code is totally untested. Vlad, your solution sounds like an improvement over mine.
Tilendor
A: 

The previous solution is really great! However, I'm looking for one more feature: is it possible to eager load last subordinate record before a specific date? This is needed so that my users can browse a history a song's votes (with links to previous and next days).

kyku