Rails Coach

025 RC Eager Loading


Listen Later

Eager loading is a terrific way of speeding up your response times. Let's consider a piece of code that pulls a list of associated objects from the database. For example, a view that displays the posts written by a given user:
<% @user.posts.each do |post| %>
<%= render post %>
<% end %>
(I know that partial has a collection option for things like this. I feel that this code sample is more expressive for our discussion.)
In this case, assuming that @user was loaded by calling User.find(1), your Rails application is going to go to the database for each post. So, if the user has 40 posts in the system, the Rails application will make 40 trips to the database to get the posts.
The problem is that if there is any latency on the database connection, it adds up.
The fix for this is the use of the 'includes' method when querying for the user. User#includes tells the query to pull in whatever associated records you specify in its arguments. So, if we found @user by calling User.includes([:posts]).find(1), it would pull the user's record and all of the user's posts records and cache all of the user's posts on the user's object.
The argument for 'includes' is an array. The objects in the array can be symbols or hashes. Symbols represent that associations the Model has. Hashes are used for including nested associations. For example, if we wanted to pull all of the comments on the user's posts. Here's another example:
# In the controller
@user = User.includes([:address, :phone_number, {:posts => [:comments]}]).find(1)
# In the view 
<% @user.posts.each do |post| %>
<%= render post %>
<% post.comments.each do |comment| %>
<%= render comment %>
<% end %> 
<% end %>
...more
View all episodesView all episodes
Download on the App Store

Rails CoachBy Charles Max Wood

  • 4.7
  • 4.7
  • 4.7
  • 4.7
  • 4.7

4.7

3 ratings


More shows like Rails Coach

View all
Teach Me To Code » Screencasts by Charles Max Wood

Teach Me To Code » Screencasts

11 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

234 Listeners

iPhreaks by Charles M Wood

iPhreaks

17 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

45 Listeners

The Freelancers' Show by Charles M Wood

The Freelancers' Show

23 Listeners

React Native Radio by Jamon Holmgren, Robin Heinze, Mazen Chami

React Native Radio

59 Listeners

My JavaScript Story by Charles M Wood

My JavaScript Story

4 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

62 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

21 Listeners

Adventures in Angular by Charles M Wood

Adventures in Angular

15 Listeners