Eager Loading

is there a way to always eagerly load an associated object so that you
don’t have to put :include into every finder?

class Product <ActiveRecord::Base
belongs_to :user #always load user when product is loaded
end

Product.find(1).user.login

#1 query since user was loaded with the product, same as if i
used :include but I don’t want to have to specify it everywhere.

i’m not aware of any config to do this automatically… perhaps
someone more experienced knows a way.

another way is to make a method in your model:

class Product <ActiveRecord::Base
belongs_to :user

def self.find_eager(id)
self.find(id, :include => :user)
end

end

note you’d have to do a little more work to get it to work with all
options to find(), like :all, :conditions, :order etc…

On 8/22/07, jemminger [email protected] wrote:

def self.find_eager(id)
self.find(id, :include => :user)
end

end

note you’d have to do a little more work to get it to work with all
options to find(), like :all, :conditions, :order etc…

I would do it similarly.

I believe this would be a good fit for with_scope

class Product <ActiveRecord::Base
belongs_to :user

def self.find_eager(*args)
with_scope( :find => { :include => [:user] } ) do
find(*args)
end
end

end

You could also alias_method_chain find on the Product class and wrap
find in
a with_scope there instead. That way could be neater.

Cheers
Daniel

On 8/22/07, Daniel N [email protected] wrote:

note you’d have to do a little more work to get it to work with all

Cheers
Daniel

I thought I’d check out how to alias_method_chain for the Product Class
to
wrap the find method. This is untested mostly. YMMV

class Product <ActiveRecord::Base
belongs_to :user

class << self
  def find_with_user_scope( *args )
    with_scope( :find => { :include => :user } ) do
       find( *args )
    end
  end
  alias_method_chain :find, :user_scope
end

end

This way whenever you call Product.find it will be scoped to include the
user. If you don’t want to include the user then you can use

Product.find_without_user_scope( *args )

HTH
Daniel