Reputation: 6042
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)?
Upvotes: 4
Views: 763
Reputation: 48923
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
# for Rails version <4:
has_one :last_vote, :class_name => 'Vote', :order => 'created_at DESC'
# for Rails version 4+
has_one :last_vote, -> { order(created_at: :desc) }, class_name: 'Vote'
this new association will always return the most recently created Vote for a Song.
To eager load it
# for Rails version <3:
songs = Song.find(:all, :conditions => 'artist_name = "frank"', :include => :last_vote)
# for Rails version 3+:
songs = Song.includes(:last_vote).where(artist_name: 'frank')
Upvotes: 9
Reputation: 6042
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).
Upvotes: 0