Skip to content


Subversion checkout URL

You can clone with
Download ZIP
eager loading (but not too eager) for ActiveRecord collections
Branch: master

Zeal: eager loading (but not too eager) for ActiveRecord collections

Sometimes you need to eager load some associations, but it's not convenient to do so at the same time as loading the original records. Zeal is a simple gem that offers a couple of different ways to trigger ActiveRecord's built-in eager loading on an array of already-retrieved records.

For Example

Let's say you want to do the equivalent of this:

User.find(:all, :limit => 10, :include => {:posts => :comments})

If you're reducing code duplication by loading Users in a before filter that's shared between multiple actions, it may not make sense to eager load the same associations for all of those pages. Instead, you can do this:

# before_filters.rb
@users = User.find(:all, :limit => 10)

# users_controller.rb
def users_and_posts_and_stuff
  @users.eager_load(:posts => :comments)

def users_and_friends_and_stuff
  @users.eager_load(:friends, :countrymen)

You can now avoid both N+1 and unnecessary preloading, while keeping your code as DRY as possible.


There are two ways to use Zeal: the nicer, more intrusive way, and the more explicit, less intrusive way.

# more_intrusive.rb
class Array
  include Zeal

@users.eager_load(:friends, :countrymen)

# less_intrusive.rb
Zeal.eager_load(@users, :friends, :countrymen)

# or alternately
@users.extend(Zeal).eager_load(:friends, :countrymen)

Your choice!

Something went wrong with that request. Please try again.