Latest reviews on the product page
Ruby · Rails · beginner · modification
Adds the data behind the new "Latest reviews" block on the product page. `app/models/review.rb` gets a `recent` scope that sorts a product's reviews and caps them at `RECENT_LIMIT` (5). `app/controllers/products_controller.rb` loads `product.reviews.recent` in `show` and merges the reviews, limited to the five public fields, into the existing product JSON as `recent_reviews`. `test/controllers/products_controller_test.rb` is a new integration test for the endpoint and its new field.
Ruby 4.0, Rails 8.1, SQLite in development and test (the claims here hold on SQLite, as run in a scratch app, and the sort is plain SQL `ORDER BY`). `config.time_zone` is the default UTC. Tables (existing, unchanged): `products (id, name NOT NULL, price_cents NOT NULL, timestamps)` and `reviews (id, product_id NOT NULL REFERENCES products, rating NOT NULL, author_name NOT NULL, body text NOT NULL, timestamps)` with an index on `(product_id, created_at)`. `Product has_many :reviews` (existing, unchanged), with no default order on the association. Reviews are posted through an existing flow, are never edited, and every posted review is public (there is no moderation state); a popular product has a few thousand. `config/routes.rb` (existing, unchanged) has `resources :products, only: :show`, and `ApplicationController` is unchanged. The product page (web app) ships separately and shows the reviews in the order the endpoint returns them. Tests are Minitest integration tests run against the SQLite test database.
Requirements
- `GET /products/:id` (existing) answers the product page's JSON. It gains a `recent_reviews` array: the product's 5 most recent reviews, newest first, so the review with the latest `created_at` comes first. Two reviews with the same `created_at` are ordered by `id`, higher `id` first.
- A product with fewer than 5 reviews returns all of them, in the same newest-first order; a product with no reviews returns `recent_reviews: []`.
- Each item has exactly `id`, `rating`, `author_name`, `body` and `created_at` (ISO 8601, UTC). Only reviews of the product in the path are included.
- Unchanged: the product's `id`, `name` and `price_cents` are returned as before, an unknown product id answers 404, and the page is public (no sign-in).
Files touched
- app/models/review.rb
- app/controllers/products_controller.rb
- test/controllers/products_controller_test.rb