Posted almost 12 years ago. Visible to the public. Repeats.

Preload associations in loaded records

Sometimes you want to fetch associations for an ActiveRecord that you already loaded, e.g. when it has deeply nested associations.

Edge Rider Archive gives your models a static method preload_associations. The method can be used to preload associations for loaded objects like this:

class UsersController < ApplicationController def show @user = User.find(params[:id]) User.preload_associations [@user], { :threads => { :posts => :author }, :messages => :sender } end end

The attached initializers remain for legacy purposes. Please prefer to use Edge Rider Archive for new projects, which is being actively maintained and has test coverage for all versions of Rails.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Arne Hartherz
Last edit:
over 1 year ago
by Arne Hartherz
preload_associations.rails2.rb, preload_associations.rails3.rb
rails, eager, loading, includes, object, instance
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more