0
0
Ruby on Railsframework~30 mins

Why caching improves response times in Ruby on Rails - See It in Action

Choose your learning style9 modes available
Why caching improves response times
📖 Scenario: You are building a simple Rails web app that shows a list of popular books. Each time a user visits the page, the app fetches the book data from a slow external source. To make the page load faster, you want to use caching.
🎯 Goal: Build a Rails controller that caches the list of books so that repeated visits load the page faster by avoiding repeated slow data fetching.
📋 What You'll Learn
Create a controller action that fetches book data
Add a cache key variable to control caching
Use Rails caching to store and retrieve the book list
Render the cached book list in the response
💡 Why This Matters
🌍 Real World
Caching is used in web apps to speed up response times by saving results of slow operations like database queries or API calls.
💼 Career
Understanding caching is important for backend developers to improve app performance and user experience.
Progress0 / 4 steps
1
Set up the books data method
In the BooksController, create a method called fetch_books that returns an array of these exact book titles: ["The Hobbit", "1984", "Pride and Prejudice"].
Ruby on Rails
Need a hint?

Define a method named fetch_books inside BooksController that returns the array exactly as shown.

2
Add a cache key variable
Inside BooksController, add a private method called cache_key that returns the string "books_list_v1".
Ruby on Rails
Need a hint?

Create a private method named cache_key that returns the string exactly as shown.

3
Use Rails caching to store and fetch books
Add an action called index in BooksController that uses Rails.cache.fetch(cache_key) to store or retrieve the books by calling fetch_books. Assign the result to @books.
Ruby on Rails
Need a hint?

Define index method that sets @books using Rails.cache.fetch(cache_key) with a block calling fetch_books.

4
Render the cached books list
In the index action, add a line to render the @books array as JSON using render json: @books.
Ruby on Rails
Need a hint?

Add render json: @books inside the index method to send the cached books as JSON response.