025 RC Eager Loading




Rails Coach show

Summary: 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: (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