Skip to content

Instantly share code, notes, and snippets.

@Deepwalker
Last active August 29, 2015 13:56
Show Gist options
  • Save Deepwalker/9216254 to your computer and use it in GitHub Desktop.
Save Deepwalker/9216254 to your computer and use it in GitHub Desktop.
Sometimes you need preload associations, not join, separate load. And with this method you can preload on arrays too!
class ApplicationController < ActiionController::Base
def preload_associations(*associations)
collection = get_collection_ivar
associations.each do |association|
ActiveRecord::Associations::Preloader.new(collection, association).run
end
set_collection_ivar collection
collection
end
end
class SomeControllerInTheWild < ApplicationController
def index
bla bla bla
preload_associations(:posts, shops: [:comments])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment