Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Rails Practice Exercises and Review

Practice Rails with graded exercises, runnable Ruby solutions, a debugging checklist, a review of the whole course and common Rails interview questions with short answers. Finish with a plan for what to learn next.

You now know the main parts of Rails: routing, controllers, views, Active Record, forms, security, testing, jobs and deployment. Knowledge fades unless you use it, so this last lesson gives you exercises, a debugging checklist, a review of the course and typical interview questions.

As in the rest of this track, the site cannot run Rails itself. The exercises are written so that the logic part can be solved in plain Ruby here, and the Rails part is described for you to try in a real app. Every runnable block below is a plain Ruby stand-in of an idea, not Rails.

Exercises

Try each one before opening the solution idea.

1. Routes by hand (easy). Write the config/routes.rb for a library: books with nested reviews, only index/show for books, a custom GET /books/search, and a root route. Run bin/rails routes and check every URL helper name. See resourceful routes.

2. N+1 hunt (easy). Take any index page that prints post.author.name for 20 posts and count the queries in the log. Fix it with includes(:author). See eager loading.

3. A validation (medium). Add a rule to Order: total_cents must be positive, and coupon_code must be blank or match /\A[A-Z0-9]{6}\z/. Write the model test first.

4. Slug generator (medium, runnable). Write a method that makes URL slugs and guarantees uniqueness by appending -2, -3... This is the logic you would put in a before_validation callback. Solve it below.

Ruby Exercise 4: unique slugs (edit and run)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The third line shows a real edge case: a title of only symbols gives an empty slug. A good solution falls back to something like "post" or the record id. Edge cases like this are what validations and tests are for.

5. Policy object (medium, runnable). Put permission rules in one object instead of scattering if statements. Complete can_edit? so admins can edit anything, authors can edit their own unpublished posts, and nobody edits a published post unless they are an admin.

Ruby Exercise 5: a plain Ruby policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In Rails you would call this from a before_action and also use it in views to hide buttons, but the server check is the one that counts. See web security and authorization.

6. A background job (hard). Write ExportPostsJob that builds a CSV of a user's posts and mails it to them. Make it idempotent, retry on timeouts, and test it with assert_enqueued_with. See jobs and caching.

7. Full feature (hard). Add "favorites" to the blog project: a user can favorite a post once, sees their favorites page, and the post shows a count. Use a join model with a unique index, a counter cache, a nested or member route, a policy, and tests.

A debugging checklist

When something breaks, work through these steps in order:

  1. Read the error and the first line of your own code in the trace. Rails traces are long; the helpful line is the first one inside app/.
  2. Check the log (log/development.log): the route matched, the parameters received, the SQL run, the template rendered.
  3. bin/rails routes -g name shows whether the route and its helper exist.
  4. bin/rails console lets you run the query or method by itself. reload! picks up code changes.
  5. Put debugger in the code (Rails ships the debug gem) and inspect variables in the terminal where the server runs.
  6. Check params: puts params.inspect shows what the form actually sent. Most "my attribute is not saved" bugs are strong parameters.
  7. Look at object.errors.full_messages when save returns false.
  8. Reproduce in a test before fixing, so the bug cannot return.

Course review

The request path

Router URL to action
Controller Params, models, render
View ERB to HTML
Model Rules and data

Convention over configuration ties them together.

1 / 2

Interview questions with short answers

  • What is convention over configuration? Rails picks sensible defaults (table names from class names, controller and view locations), so you write code only for what differs.
  • Explain MVC in Rails. The router sends a request to a controller action, which uses models (data and rules) and renders a view (HTML).
  • What is the N+1 problem and the fix? One query for a list plus one per item. Use includes, preload or eager_load.
  • includes vs joins? joins builds an SQL join, usually to filter; includes loads associations to avoid N+1 and may use a join or a second query.
  • What are strong parameters? A whitelist of permitted attributes (params.expect / permit) that blocks mass assignment of fields like admin.
  • render vs redirect_to? render outputs a template in the current request; redirect_to sends 302/303 so the browser makes a new request. Redirect after a successful POST, render with 422 on failure.
  • How does Rails prevent CSRF, XSS and SQL injection? CSRF tokens on non-GET forms, escaped ERB output, and parameterized queries (where("name = ?", name) or hashes), never string interpolation.
  • What is a migration? A versioned Ruby file that changes the schema; Rails tracks which have run in schema_migrations.
  • What do callbacks risk? Hidden side effects and ordering problems; use them for the model's own consistency and move business workflows to explicit service or form objects.
  • How do you handle slow work? Active Job on a queue backend, with idempotent jobs and retries.
  • How would you cache a page? HTTP caching with ETags, fragment caching with key-based expiration, and Rails.cache.fetch for computed data.

Where next

Pick a direction and build something real:

  • Hotwire: Turbo and Stimulus give you modern, fast pages without writing a single-page app.
  • APIs: versioned JSON APIs, serializers and token authentication (API tokens).
  • Performance and scale: database indexes, query plans, caching, background jobs.
  • Ruby itself: a stronger Ruby makes Rails easier; see the Ruby tutorial.
  • Contribute or read: the Rails source is readable Ruby. Read how resources or has_many are built.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A form saves nothing and shows no error. What is the most common cause to check first?

    Unpermitted parameters are dropped silently (or logged). Check the log for 'Unpermitted parameter' and your params.expect list.
  2. 2. What should happen after a successful POST that creates a record?

    Redirecting avoids a duplicate submission when the user refreshes, and shows the new state through a GET.
  3. 3. Which pair is correct for loading authors with posts efficiently?

    includes loads the authors in one extra query (or a join) instead of one per post.
  4. 4. In which place must an authorization rule be enforced for it to count?

    Anyone can send a request without your buttons. Hiding UI is a courtesy, not security.

Summary

  • Practice by building: solve the exercises, then add features to the blog project.
  • Debug in order: error line, log, routes, console, debugger, params, errors, a failing test.
  • Know the core ideas well enough to explain them: MVC, conventions, N+1, strong parameters, CSRF/XSS/SQL injection, migrations, jobs and caching.
  • Keep going with Hotwire, APIs and performance, and keep reading real Rails code.

Back to the Ruby on Rails track.