190 Pagination [0.5d]

Updated . Posted . Visible to the public.

Rendering thousands of records on one page is slow. Pagination loads one page at a time and keeps large lists fast.

Important

Work on this lesson in advisor mode.

Learning goals

  • You can explain why rendering a large collection on one page is slow — queries, object instantiation, rendering — and how pagination avoids it.
  • You can add pagination to a list with a gem (e.g. will_paginate) and style its controls to match the app.
  • You can read the queries pagination produces (a LIMIT/OFFSET query and a count) and explain what each is for.
  • You can read a request in the development log and tell where its time went, e.g. views vs. database.
  • You can measure what a user actually experiences: load time and response size in the DevTools Network tab, with throttling simulating a slow connection.
  • You can create large amounts of test data quickly, e.g. inside a single transaction.

Resources

Read what's new to you, skim what's familiar, skip what you already master. Stop when you can meet the learning goals.

Your agent can also generate an overview, a tutorial or an explanation for anything here, tailored to what you already know. Just ask.

Exercises

Work on your local development server throughout — no staging needed here.

Create a slow page

  • Create 7500 movies in MovieDB (hint: doing it in a single transaction is much faster).

Measure the server

  • tail -f log/development.log and load the movies index. Learn to read the request log: which queries ran, and the final Completed 200 OK in …ms (Views: … | ActiveRecord: …) line. Where does the time go?

Measure the browser

  • The server time is not what a user feels: the HTML must also travel over the network, and the browser must build the page from it. Open your browser's DevTools, find the Network tab and throttle to "Slow 4G". Reload and find the request row for the index HTML document. How long did it take, and how large is the response?

Paginate

  • Use the will_paginate gem to add pagination to MovieDB's list of movies.
  • Inspect the HTML generated by will_paginate. Customize the style so it matches the look of your MovieDB.
  • In the development log, see which queries will_paginate generates. What does each of them do?
  • Repeat both measurements — request log and throttled Network tab — and compare them with the numbers from before.
Profile picture of Henning Koch
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra Curriculum (2015-07-08 17:29)