Skip to content

Instantly share code, notes, and snippets.

@juno
Last active June 3, 2018 07:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juno/b3019c6f86524dadcef2 to your computer and use it in GitHub Desktop.
Save juno/b3019c6f86524dadcef2 to your computer and use it in GitHub Desktop.
Preload ActiveRecord associations. (Rails 4.2.5)
# You can preload associations explicitly.
# This method also can apply to polymorphic association.
#
# See also https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/preloader.rb
#
def index
@comments = Comment.order(id: :desc).limit(10)
# This prevents N+1 query for user and commentable associations
ActiveRecord::Associations::Preloader.new.preload(@comments, [:user, :commentable])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment