Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager loading last subordinate record

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)?

like image 717
kyku Avatar asked Feb 28 '23 22:02

kyku


1 Answers

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')
like image 112
Tilendor Avatar answered Mar 11 '23 18:03

Tilendor