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)?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With