File: eager_loading.rb

# eager_loading.rb

Path: | lib/sequel_model/eager_loading.rb
Last Update: | Fri Feb 27 15:40:22 -0700 2009

Eager loading makes it so that you can load all associated records for a set of objects in a single query, instead of a separate query for each object.

Two separate implementations are provided. eager should be used most of the time, as it loads associated records using one query per association. However, it does not allow you the ability to filter based on columns in associated tables. eager_graph loads all records in one query. Using eager_graph you can filter based on columns in associated tables. However, eager_graph can be much slower than eager, especially if multiple *_to_many associations are joined.

You can cascade the eager loading (loading associations’ associations) with no limit to the depth of the cascades. You do this by passing a hash to eager or eager_graph with the keys being associations of the current model and values being associations of the model associated with the current model via the key.

The arguments can be symbols or hashes with symbol keys (for cascaded eager loading). Examples:

      Album.eager(:artist).all
      Album.eager_graph(:artist).all
      Album.eager(:artist, :genre).all
      Album.eager_graph(:artist, :genre).all
      Album.eager(:artist).eager(:genre).all
      Album.eager_graph(:artist).eager(:genre).all
      Artist.eager(:albums=>:tracks).all
      Artist.eager_graph(:albums=>:tracks).all
      Artist.eager(:albums=>{:tracks=>:genre}).all
      Artist.eager_graph(:albums=>{:tracks=>:genre}).all

[Validate]