Last active
June 3, 2018 07:42
-
-
Save juno/b3019c6f86524dadcef2 to your computer and use it in GitHub Desktop.
Preload ActiveRecord associations. (Rails 4.2.5)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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