Lesson Tuesday

Now that we're seeding our databases, it no longer makes sense to call a method like Album.all. We wouldn't want our application to return ten thousand results if there are that many albums in the database. A user could make a search to narrow the number of results further but there may still be thousands of albums of a specific genre in the database as well.

How can we solve this problem? We could limit the search to a certain number of albums but that would also limit the ability of our users to browse through the available albums. We could also create a scope based on the first letter of an album to narrow down results, but more common letters could still have many albums.

Another common solution is to paginate the results. In the last course section, we discussed how we can use OFFSET with SQL to specify which results should be returned. For example, we could return the first ten results, the next ten results, and so on.

While we could create our own custom solution, there are popular gems that will do this work for us. The most commonly used tools are the kaminari gem and the will_paginate gem. We recommend the kaminari gem because it has more commits, more recent commits, and uses Travis CI to verify that the build is passing and maintained. However, both gems are effective.

Kaminari provides a built-in page scope that will figure out the needed offset. We can also chain a per method to customize exactly how many results should show per page. Check out the documentation for implementation.

You are not expected to paginate results for this section's independent project but you are encouraged to experiment with a pagination gem if you have the time.

Lesson 18 of 27
Last updated July 14, 2022