skip to content

Ruby on Rails

2 roadmaps621 questionsupdated

The convention-over-configuration Ruby framework: Active Record, Action Pack, Active Job and a deploy-ready generated app. Interviewers probe whether you work with its conventions, not against them.

on this pageshow

guide

overview

~2 min

Ruby on Rails is a full-stack web framework for Ruby built on convention over configuration: name a model, a table, a controller and a route the expected way, and the pieces find each other with almost no wiring. Interviewers probe whether you work with those conventions or against them. Can you predict the SQL a query chain will run, say which save path skips the model's own rules, list what a freshly generated app ships with, and decide where code belongs when the default stops fitting? A strong Rails answer names the default, explains why it exists, and says what changes when you step off it. The hub follows a request and the application around it. [Project anatomy and startup](/topics/be-rails-foundations) and the [command line toolkit](/topics/be-rails-cli) cover how an app is laid out, booted and generated. The model layer is the largest part: [Active Record models](/topics/be-rails-active-record), [associations](/topics/be-rails-associations), the [query interface](/topics/be-rails-querying), [migrations](/topics/be-rails-migrations) and [database adapters](/topics/be-rails-databases). The web layer runs from [routing](/topics/be-rails-routing-controllers) through [controllers](/topics/be-rails-controllers) to [views](/topics/be-rails-views-hotwire), [forms](/topics/be-rails-forms) and [front-end assets](/topics/be-rails-assets), with [API-only apps](/topics/be-rails-api) as the trimmed variant. Work outside the request cycle lives in [Active Job](/topics/be-rails-active-job-cable), [Action Cable](/topics/be-rails-action-cable), [mailers](/topics/be-rails-mailers) and [file storage](/topics/be-rails-storage). Cross-cutting sections cover [Active Support](/topics/be-rails-active-support), [caching](/topics/be-rails-caching), [logins and permissions](/topics/be-rails-auth), [security](/topics/be-rails-security), [translations](/topics/be-rails-i18n), [pagination](/topics/be-rails-pagination), [engines](/topics/be-rails-engines), [testing](/topics/be-rails-conventions-testing), [diagnostics](/topics/be-rails-diagnostics) and [deployment](/topics/be-rails-deployment). Junior rounds check fluency: the resourceful routes, how a form posts back, what a migration records. Middle and senior rounds turn to cost and failure: N+1 queries, migrations that lock a busy table, jobs that run before the data they need is committed, a server config that leaves cores idle. Principal rounds ask how to upgrade across major versions, when to carve a monolith into engines, and which generated defaults to keep. Start with the app's anatomy and naming rules, then Active Record and querying, because most of the framework assumes them. Routing and controllers come next; jobs, caching, security and deployment make sense once the path of a single request is clear.

primer

### Conventions are the wiring Rails replaces configuration with naming rules. A class name implies a file path, a table, a controller, route helpers and foreign key columns, and the autoloader finds constants in the file tree by the same rules. Most questions about Rails "magic" reduce to which convention is at work. Knowing the rule lets you predict behaviour; knowing how to override it, with a custom table name, an inflection or a non-resourceful route, is what interviewers test next. ### A model is a table, and saving has paths Each Active Record class wraps one table and each instance one row. A normal save runs a pipeline: validations, then callbacks around the write, then hooks that fire after the transaction commits. Several methods deliberately skip parts of that pipeline for speed, and picking the wrong one bypasses rules the model was meant to enforce. A good answer names which path a call takes and what it leaves out. ### Relations are lazy SQL Chained query methods build a relation object and run nothing until something needs the records. That laziness makes scopes composable and reusable, but it also hides how many queries a page issues. Predicting the SQL, and the number of round trips, behind a chain is the central skill of the [query interface](/topics/be-rails-querying); the N+1 pattern is its most common failure. ### A request walks a fixed stack A request passes through Rack middleware, the router, a controller's filter chain and one action, which renders a template or redirects. Strong parameters guard the edge where user input meets the model. Each layer has a conventional default, such as implicit rendering, RESTful routes and escaped output, and questions ask what happens when you leave it. ### Slow work leaves the request Email, file processing and calls to other services belong in background jobs. Active Job gives them one API over swappable backends, so the questions are about what a job may assume: its arguments are serialized, it may run more than once, and it may start before the data it needs is visible unless the design prevents it. ### Rails ships production defaults A new app arrives with a Dockerfile, a Puma config, encrypted credentials, forgery protection, a health check route, and database-backed production adapters for queues, caching and WebSockets. Senior answers are about these defaults: which are safe as generated, which need tuning under real traffic, and which you swap out as the app grows. ### One application, then seams Rails favours a single application that does a lot. Concerns, plain service objects, namespaces and engines are ways to add seams inside that monolith without splitting it into services. At senior level, interviewers ask where you would draw those seams and what each one costs in indirection.

Convention over configuration
The Rails doctrine that sensible defaults and naming rules replace explicit setup, so code that follows them needs little wiring and code that departs from them must say so.
Active Record
Both the ORM pattern and the Rails library that implements it: a model class wraps a table, an instance wraps a row, and persistence, validations and associations live on the model.
Relation
The lazy, chainable query object returned by where, order, joins and scopes. It runs its SQL only when records are actually needed, for example when iterated.
N+1 query
Loading a list with one query, then issuing one more query per row to read an association. Eager loading replaces them with a fixed number of queries.
Migration
A timestamped Ruby class that changes the database schema. The database records which versions have run, so each environment applies only the ones it is missing.
Strong parameters
The controller-side allow-list deciding which request keys may reach mass assignment; parameters that were never permitted cannot be handed to a model.
Callback
A hook run at a fixed point in a model or controller lifecycle, such as before validation, after commit or before an action. Convenient, and a common source of hidden coupling.
Concern
A module built with ActiveSupport::Concern that bundles instance methods, class methods and setup run on inclusion, used to share behaviour across models or controllers.
Zeitwerk
The autoloader Rails uses. It maps constant names to file paths, loads code on first reference, reloads it in development and eager-loads it in production.
Rack middleware
A layer wrapping the application that sees every request and response before and after the router; Rails assembles a stack of them for sessions, cookies, logging and security.
Resourceful routing
Declaring a resource in config/routes.rb to get the standard RESTful routes, controller actions and path helpers in one line instead of mapping each URL by hand.
Partial
A view template whose file name starts with an underscore, rendered inside other templates to reuse markup, often once per record in a collection.
Hotwire
The default Rails front-end approach: Turbo updates pages with server-rendered HTML over links, forms and streams, and Stimulus attaches small JavaScript controllers to that HTML.
Active Job
The framework's background job API: a class with a perform method, enqueued with arguments and executed later by whichever queue backend the app configures.
Solid Queue
The database-backed Active Job backend that new Rails 8 apps use by default, alongside Solid Cache and Solid Cable for caching and WebSocket pub/sub.
Encrypted credentials
Secrets committed to the repository in encrypted form and decrypted at boot with a master key kept outside it, read through Rails.application.credentials.
Engine
A packaged mini-application with its own models, controllers, routes and migrations that a host app loads or mounts; a Rails application is itself a specialised engine.
Russian-doll caching
Nesting cached view fragments whose keys change with their records, so touching a child refreshes the chain of fragments around it while untouched siblings are reused.
GVL
CRuby's global VM lock: in ordinary code only one thread per process executes Ruby at a time, which is why Puma combines threads with forked worker processes.

Trace one request. Puma accepts the connection and hands it to the app as a Rack request; middleware handles sessions, cookies, request ids and security checks before the router matches the verb and path to a controller action. The controller runs its before-filters, typically authentication and record loading, permits parameters and talks to models. Active Record turns those calls into SQL through the configured adapter and wraps writes in transactions. The action then renders a view, composing a layout, partials and helpers into escaped HTML or JSON, or it redirects. Anything slow is enqueued as a job and runs later in a worker process that boots the same application. The other sections attach to this path rather than sitting beside it: - **Active Support** sits under every layer: core extensions, concerns, time zones, and the notifications that logging and instrumentation subscribe to. - **Caching** wraps views and computed values; **security** defaults live mostly in middleware and controller settings; **authentication** is usually a before-filter backed by a session or a token. - **Mailers, storage and Action Cable** reuse the same parts: mailers are controller-like classes with their own views, usually sent from a job; attachments are associated records; channels share the app's notion of the current user. - **Engines and Railties** hook into boot, and **deployment** decides how many processes and threads run all of it. The sketch below shows routing, the parameter allow-list, a save path and background delivery meeting in one action: ```ruby # config/routes.rb resources :orders, only: %i[new create show] # app/controllers/orders_controller.rb class OrdersController < ApplicationController def create @order = Order.new(params.expect(order: [:sku, :quantity])) if @order.save OrderMailer.confirmation(@order).deliver_later redirect_to @order else render :new, status: 422 end end end ``` Each line leans on a convention. The route names the controller and the helpers `redirect_to` relies on, `params.expect` is the allow-list, the non-bang `save` reports failure with a boolean so the form can re-render with its errors, and `deliver_later` hands sending to a job instead of the request.

  1. Project Anatomy & Startup →

    How an app is generated, laid out, named and booted; every other section assumes these conventions.

  2. Active Record Models →

    Models, save paths, validations and callbacks: the layer most Rails code and most questions lean on.

  3. Query Interface →

    Predicting the SQL and query count behind a relation, including eager loading and the N+1 problem.

  4. Route Mapping DSL →

    How URLs and verbs map to controller actions through resourceful routes and path helpers.

  5. Action Controller Layer →

    What an action does with a request: parameters, filters, rendering, sessions and error handling.

  6. Active Job →

    Moving slow work out of the request, and what a job must assume about retries and the data it reads.

  • Reaching for update_column or update_all for speed without saying they skip validations and callbacks — see Create, Update & Destroy.

  • Iterating records in a view and reading an association on each row without eager loading, then blaming the database for a slow page.

  • Interpolating request values into a where string instead of using hash conditions or placeholders, which opens the query to SQL injection.

  • Enqueuing a job inside a transaction without checking whether the app defers enqueuing until commit; otherwise the worker can run before the row it needs is visible.

  • Expecting a non-bang update inside a transaction block to roll it back on invalid data; it only returns false, and the block rolls back on an exception.

  • Adding an index or changing a column on a large live table in a plain migration without considering the locks it takes — see Lock-Safe Changes.

  • Running the generated Puma config unchanged on a multi-core host and wondering why throughput stalls while most cores sit idle.

  • Calling Time.now or Date.today in application code instead of the zone-aware forms, which shifts times, and near midnight dates, by the server's offset.

  • Building a Delete control with a plain link: following a link is a GET, so it cannot correctly reach the destroy action.

  • Putting business workflows in model callbacks; they fire on every save path that runs them, couple unrelated code and make models hard to test.

This guide assumes Rails 8.1. Many production apps run older releases, and interviewers often ask what an upgrade changed or which era a habit comes from: - **7.0** made Zeitwerk the only autoloader, dropping the classic one, and made import maps and Hotwire the defaults for new apps. - **7.1** started generating a production Dockerfile and added `normalizes` for cleaning attribute values. - **8.0** made Propshaft the default asset pipeline, set Solid Queue, Solid Cache and Solid Cable as the default backends, added an authentication generator, introduced `params.expect`, and paired generated apps with Kamal 2 and Thruster for deployment. - **8.1** added continuable jobs, which can resume from a recorded step after a worker restarts. When an answer depends on a default, such as the asset pipeline, the queue backend or how sign-in is generated, say which version you mean. Upgrade questions usually come back to `config.load_defaults`: an upgraded app runs the new framework code while keeping the old defaults, then adopts the new ones one setting at a time through the generated new-defaults initializer before raising the version it loads.

Rails is placed against other batteries-included server frameworks: Django in Python, Laravel in PHP, Phoenix in Elixir and Spring Boot on the JVM. All of them bundle an ORM, routing, templating and migrations. The differences an interviewer expects you to name are the runtime, where Ruby's lock and process-per-core model contrasts with Phoenix's lightweight processes or the JVM's threads, and how strongly each prefers convention to explicit configuration. Against minimal frameworks such as Sinatra or Express, Rails trades flexibility for a shared structure any Rails developer recognises. Much of a real Rails app is gems rather than the framework. Devise, Pundit and CanCanCan cover sign-in and authorization; Sidekiq is the long-standing Redis-backed job backend that Solid Queue now competes with; RSpec and factory_bot are common alternatives to Minitest and fixtures; ViewComponent and Phlex give views a class-based component model. On the front end, Hotwire competes with pairing an API-only Rails backend and a separate JavaScript single-page app, and that choice decides whether views stay server-rendered. [Front-End Asset Builds](/topics/be-rails-assets) and [API-Only Apps](/topics/be-rails-api) cover both sides.

explore

report an issue with this guide →

questions

621 · 27 sections

In a Rails 8.1 app, why does an edited model take effect without a restart in development but not in production?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Development sets config.enable_reloading = true, so after a file changes Rails unloads autoloaded application constants before the next request, which autoloads fresh code. Production sets enable_reloading = false and eager_load = true, loading all code once at boot.

open as a page

In a Rails 8.1 app, what do config/boot.rb, config/application.rb and config/environment.rb each do at startup?

level: juniorimportance: must knowfreq 52%
basics
~10 s

config/boot.rb makes the Gemfile's gems loadable. config/application.rb loads Rails, requires the app's gems and defines the Application class with its settings. config/environment.rb requires it and calls Rails.application.initialize!, which runs every initializer.

open as a page

What do convention over configuration and DRY mean in Rails, and which configuration does a Rails CRUD for people never write because of them?

level: juniorimportance: must knowfreq 70%
basics
~20 s

In Rails, convention over configuration means names and locations imply behaviour, and DRY means each fact lives in one place; a people CRUD declares no table mapping, columns, routes per action, template paths or form URLs, because Rails derives them.

open as a page

In a Rails genealogy app, which names does a Person model imply for its table, files, controller, routes, views and foreign keys?

level: juniorimportance: must knowfreq 80%
basics
~10 s

A Rails Person model lives in app/models/person.rb and maps to the people table; PeopleController handles resources :people, with helpers like people_path and person_path, templates under app/views/people, and other tables point at it through person_id.

open as a page

In a Rails 8.1 app, what does each folder under app/ hold, and which base classes does rails new put there?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Rails 8.1's app/ is split by role: models, controllers, views, helpers, mailers, jobs, assets and javascript. rails new seeds each Ruby folder with an Application* base class, such as ApplicationRecord and ApplicationController, that the app's own classes inherit from.

open as a page

In a Rails 8.1 app, what do bin/rails server, console, dbconsole and runner each start, and when do you reach for each?

level: juniorimportance: must knowfreq 68%
basics
~20 s

bin/rails server boots the app under Puma on port 3000; console opens IRB with the app loaded; dbconsole opens the database's own client (psql, mysql, sqlite3) from database.yml; runner boots the app, runs one Ruby string or file, and exits.

open as a page

In a Rails 8.1 app, where do custom Rake tasks live, and what does bin/rails generate task loyalty recompute write?

level: juniorimportance: must knowfreq 58%
basics
~20 s

Custom tasks live in .rake files under lib/tasks, which the app's Rakefile loads through Rails.application.load_tasks. bin/rails generate task loyalty recompute writes lib/tasks/loyalty.rake with a loyalty namespace and a recompute task stub that has desc "TODO" and the :environment prerequisite.

open as a page

In Rails 8.1, what do bin/rails generate model, controller, resource and scaffold each write, and when do you pick resource over scaffold?

level: juniorimportance: must knowfreq 72%
basics
~20 s

model writes a migration, model class, model test and fixture; controller writes named actions, their views, a helper, a test and get routes; resource adds an empty controller and resources route to the model files; scaffold adds a full CRUD controller, ERB views and JSON views.

open as a page

In Rails 8.1, how do RAILS_ENV and the -e flag decide which environment bin/rails console, runner and server boot into?

level: middleimportance: must knowfreq 55%
basics
~20 s

Without a flag, bin/rails uses RAILS_ENV, then RACK_ENV, then development. The -e flag on server, console, runner and dbconsole overrides that for one command; Rake tasks such as db:migrate have no -e, so they need RAILS_ENV=production in front.

open as a page

In a Rails 8.1 Rake task, what does the :environment prerequisite actually load, and what changes when the task also takes arguments?

level: middleimportance: must knowfreq 50%
basics
~20 s

The Rakefile only loads config/application.rb; the :environment prerequisite runs Rails' environment task, which requires config/environment.rb and initializes the app, without eager loading by default. With arguments the form is task :recompute, [:store_id] => :environment, called as bin/rails "loyalty:recompute[42]".

open as a page

In Rails, what is the difference between a named route's _path and _url helpers, and when do you need the _url form?

level: juniorimportance: must knowfreq 72%
basics
~10 s

Both come from the same route name: class_session_path(@session) returns "/class_sessions/42", class_session_url(@session) adds scheme, host and port. Use _url whenever the link leaves the current page: emails, calendar invites, API payloads, feeds.

open as a page

In Rails, how do you list an app's routes with bin/rails routes, and what do its -c, -g and --expanded options do?

level: juniorimportance: must knowfreq 62%
basics
~20 s

bin/rails routes prints every route in match order as Prefix, Verb, URI Pattern and Controller#Action. -c filters by controller, -g greps names, verbs, paths and actions (or a concrete URL), and --expanded prints one block per route.

open as a page

In config/routes.rb, which routes, helper names and params does resources :episodes nested inside resources :shows produce?

level: juniorimportance: must knowfreq 72%
basics
~10 s

Nesting puts /shows/:show_id in front of all seven episode routes, prefixes the helpers (show_episodes_path(show), show_episode_path(show, episode)), passes params[:show_id] next to params[:id], and still dispatches to a plain EpisodesController.

open as a page

In config/routes.rb, which seven routes does resources :photos generate, with their HTTP verbs, paths, controller actions and named helpers?

level: juniorimportance: must knowfreq 85%
basics
~10 s

resources :photos draws index and create on /photos, new on /photos/new, and show, edit, update and destroy on /photos/:id, all handled by PhotosController, with helpers photos_path, new_photo_path, edit_photo_path and photo_path.

open as a page

In config/routes.rb, how do you restrict a :year segment to four digits, and why does Rails reject ^ or \A in that regex?

level: middleimportance: must knowfreq 52%
basics
~20 s

Give the segment a regexp, as in constraints: { year: /\d{4}/ } or the shorthand year: /\d{4}/. Rails matches it against the whole segment already, so ^, \A, $ or \z raise an ArgumentError when the routes load.

open as a page

In a Rails controller, what does an action render when it never calls render or redirect_to, and how do its instance variables reach the view?

level: juniorimportance: must knowfreq 80%
basics
~10 s

An action that ends without rendering gets the template named after its controller and action, such as app/views/vendors/index.html.erb, and every instance variable the controller set is copied into that view; local variables are not.

open as a page

In a Rails controller, what does before_action :set_bouquet, only: %i[show edit update destroy] do, and why do scaffolds generate it?

level: juniorimportance: must knowfreq 82%
basics
~20 s

It runs the private set_bouquet method before show, edit, update and destroy, so each starts with @bouquet already loaded from the id in the URL; scaffolds generate it so the lookup is written once instead of four times.

open as a page

In a Rails 8.1 app in production, why does Track.find with an id that does not exist show a 404 page instead of a 500?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Track.find raises ActiveRecord::RecordNotFound, which Active Record maps to :not_found in config.action_dispatch.rescue_responses. In production the ShowExceptions middleware turns the unhandled exception into a 404 and serves public/404.html.

open as a page

In a Rails controller, what happens if you pass params[:job_application] straight to JobApplication.new, and how do strong parameters fix it?

level: juniorimportance: must knowfreq 82%
basics
~10 s

params[:job_application] is an unpermitted ActionController::Parameters, so Active Record raises ActiveModel::ForbiddenAttributesError. Strong parameters fix it with an allow-list, params.expect(job_application: [...]), which returns a permitted copy holding only the listed keys.

open as a page

In a Rails controller, how does render :show differ from redirect_to @ticket at the end of a ticket update action?

level: juniorimportance: must knowfreq 80%
basics
~20 s

render :show builds the show template inside the same PATCH request, using update's instance variables and running none of show's code. redirect_to @ticket answers with a 3xx and a Location header, so the browser sends a new GET that runs the show action.

open as a page

In Rails 8.1, what does generating an app with rails new --api change compared with a default rails new app?

level: juniorimportance: must knowfreq 60%
basics
~10 s

rails new --api makes ApplicationController inherit ActionController::API, sets config.api_only = true to trim browser middleware and generators, and skips the asset pipeline and JavaScript; jbuilder and rack-cors arrive commented out.

open as a page

In a Rails controller, what does render json: @flights do, and how do only:, except:, methods: and include: shape the output?

level: juniorimportance: must knowfreq 65%
basics
~10 s

render json: @flights calls to_json, which runs as_json and, for Active Record, serializable_hash on each record. only: and except: choose columns, methods: adds method results, and include: nests associations with their own options.

open as a page

In a Rails API app, how do you configure rack-cors in config/initializers/cors.rb for a single-page app served from another origin?

level: middleimportance: must knowfreq 55%
basics
~20 s

Uncomment gem "rack-cors" and the block in config/initializers/cors.rb, then insert Rack::Cors at position 0 with an allow block naming the SPA's exact origin and a resource listing the paths, methods and request headers it may use.

open as a page

In a Rails 8.1 API controller, how do you return a failed save's validation errors as JSON, and what shapes can the errors object produce?

level: middleimportance: must knowfreq 55%
basics
~10 s

render json: booking.errors, status: :unprocessable_content sends a Hash of attribute names to message arrays. as_json(full_messages: true) gives full sentences, full_messages a flat list, and details machine-readable codes such as :blank.

open as a page

In Rails 8.1, which ActionController::Base features does ActionController::API leave out, and how do you add one back?

level: middleimportance: should knowfreq 45%
basics
~10 s

ActionController::API drops layouts, helpers, respond_to, cookies, flash, forgery protection and the HTTP authentication helpers, and an action without render answers 204. Add a feature back by including its module, such as ActionController::MimeResponds, in ApplicationController.

open as a page

In an Active Record model, in what order do the lifecycle callbacks run when save is called on a new record?

level: juniorimportance: must knowfreq 74%
basics
~10 s

Saving a new Active Record object runs before_validation, after_validation, before_save, around_save, before_create, around_create, the INSERT, after_create, after_save, then after_commit once the transaction commits. Updates swap each create hook for its update twin.

open as a page

In a Rails 8.1 app, what does an Active Record model inheriting from ApplicationRecord get from its table's schema without declaring any attributes?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Active Record reads the table's columns when the class first needs them and defines a typed reader, writer and ? method for each, seeds new records with column defaults and treats the primary key as id; ApplicationRecord itself is abstract and has no table.

open as a page

In Active Record, what do save, create and update return when a record is invalid, and how do save!, create! and update! differ?

level: juniorimportance: must knowfreq 85%
basics
~10 s

save and update return false and fill errors; create returns the object unsaved, with errors. The bang versions raise ActiveRecord::RecordInvalid for failed validations and ActiveRecord::RecordNotSaved when a before callback aborts.

open as a page

In a Rails 8.1 Order model, what does enum :status, { placed: 0, baking: 1, out_for_delivery: 2, delivered: 3 } give you?

level: juniorimportance: must knowfreq 64%
basics
~20 s

An integer status column read and written by name: order.status returns "baking", baking? and baking! check and save a value, Order.baking and Order.not_baking are scopes, and Order.statuses holds the label-to-integer map. Unknown values raise ArgumentError.

open as a page

In an Active Record model, when do validations run, and how does a failed validation stop a save and report why?

level: juniorimportance: must knowfreq 82%
basics
~20 s

save, save!, create, update and their bang forms call valid? before writing; valid? clears errors, runs every validation for the :create or :update context, and any error stops the write, with the reasons left in record.errors.

open as a page

In an Active Record Survey model, what does accepts_nested_attributes_for :questions add, and how does one save write the survey with its questions?

level: juniorimportance: must knowfreq 50%
basics
~10 s

accepts_nested_attributes_for :questions defines a questions_attributes= writer and turns on autosave, so nested hashes build or update questions in memory and one survey save writes everything in a single transaction.

open as a page

In an Active Record has_many, what do dependent: :destroy, :delete_all, :nullify and :restrict_with_error each do when the owner is destroyed?

level: juniorimportance: must knowfreq 72%
basics
~20 s

dependent: :destroy loads each child and destroys it with callbacks; :delete_all removes them in one SQL DELETE without callbacks; :nullify sets their foreign key to NULL; :restrict_with_error refuses, adding an error so destroy returns false. Without the option nothing happens.

open as a page

In an Active Record model, how do belongs_to, has_one and has_many differ, and which table holds the foreign key for each?

level: juniorimportance: must knowfreq 80%
basics
~20 s

belongs_to sits on the model whose table holds the foreign key (books.author_id). has_one and has_many sit on the other model and find rows pointing back at it: has_one returns one record or nil, has_many an association collection.

open as a page

In Active Record single-table inheritance, what does the type column store, and how does it shape queries and loaded objects?

level: middleimportance: must knowfreq 48%
basics
~20 s

Active Record STI keeps every subclass in the parent's table and writes the class name into the type column. Subclass queries add a type filter, and each loaded row is instantiated as the class its type names.

open as a page

In an Active Record belongs_to, what do counter_cache: true and touch: true keep in sync on the parent, and what bypasses them?

level: middleimportance: must knowfreq 60%
basics
~20 s

counter_cache: true keeps boards.cards_count up to date on card create, destroy and board change, so board.cards.size needs no COUNT query. touch: true sets the board's updated_at whenever a card changes. Both are callbacks, so delete_all, update_column and insert_all bypass them.

open as a page

In Active Record, why use find_each instead of Member.all.each to re-score a million loyalty members, and how does it page through the table?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Member.all.each loads every row into memory before the loop starts; find_each loads 1,000 members at a time in primary-key order, continuing with WHERE id > the last id seen, so memory stays flat however large the table grows.

open as a page

In Active Record, what SQL does where generate when a hash condition's value is nil, an array, or a Ruby range?

level: juniorimportance: must knowfreq 72%
basics
~20 s

The value's type picks the operator: a scalar gives =, nil gives IS NULL, an array gives IN (...), and a range gives BETWEEN, or >=, < and <= comparisons for exclusive and open-ended ranges. Keys are ANDed together.

open as a page

In Active Record, which queries does Order.includes(:customer, line_items: :wine) run for an orders page printing customers, items and wines?

level: juniorimportance: must knowfreq 82%
basics
~20 s

With no conditions on the associations, it runs four queries in total: one for the orders, then one IN-list query each for customers, line items and wines, so order.customer and line_item.wine read from memory instead of querying per row.

open as a page

In Active Record, what SQL do joins and left_joins generate from association names, and how do you filter on the joined table?

level: juniorimportance: must knowfreq 74%
basics
~20 s

joins(:appointments) adds an INNER JOIN built from the association, so only doctors with appointments remain; left_joins(:appointments) adds a LEFT OUTER JOIN and keeps every doctor. Filter on the joined table with where(appointments: { starts_at: range }).

open as a page

In Active Record, when does Article.published.featured.order(:published_at) actually query the database, and what do load, loaded? and reset do?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Building the chain runs no SQL; the SELECT runs when records are first needed, such as on each or to_a. load runs it now and returns the relation, loaded? reports cached records, and reset discards them.

open as a page

In a Rails 8.1 app, how does config/database.yml declare each environment's connection, and what do its ERB tags and &default anchor do?

level: juniorimportance: must knowfreq 58%
basics
~20 s

config/database.yml holds one top-level block per environment, picked by RAILS_ENV. Rails renders the file as ERB before parsing the YAML, so ENV lookups fill in values, and a &default anchor merged with <<: *default shares the common keys.

open as a page

In a Rails 8.1 app on MySQL, why does database.yml set encoding: utf8mb4, and what does adding collation: change?

level: juniorimportance: must knowfreq 45%
basics
~20 s

utf8mb4 is MySQL's full UTF-8, so emoji and other four-byte characters survive; Rails sends SET NAMES utf8mb4 on each connection. collation: adds COLLATE to that, choosing how strings compare and sort, and the common _ci collations are case-insensitive.

open as a page

In a Rails 8.1 app on PostgreSQL, how do you add a jsonb column for sneaker details and find sneakers by one key inside it?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Add it with t.jsonb :details, null: false, default: {} and Active Record hands you a Ruby Hash with string keys. Query a key with a SQL fragment such as where("details ->> 'brand' = ?", "Nike"); where(details: {...}) compares the whole document.

open as a page

In a new Rails 8.1 app on SQLite, where do the database files live, and why must that directory survive every deploy?

level: juniorimportance: must knowfreq 50%
basics
~20 s

SQLite databases live as files under storage/ (storage/development.sqlite3, storage/test.sqlite3, storage/production.sqlite3 and its cache, queue and cable siblings). The file is the database, so production's storage/ must sit on a persistent disk or a redeploy wipes the data.

open as a page

In Active Record, what does wrapping two wallet updates in a transaction block guarantee, and which failures inside the block actually roll it back?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A transaction block makes the writes inside it commit together or not at all on one connection. It rolls back when an exception leaves the block; update returning false is not an exception, so use update! or raise yourself.

open as a page

In Rails, what do bin/rails db:migrate and bin/rails db:rollback STEP=2 do, and how does each decide which migrations to run?

level: juniorimportance: must knowfreq 75%
basics
~20 s

db:migrate runs every migration file whose version has no row in the schema_migrations table, oldest first, inserting a row after each. db:rollback STEP=2 runs the down direction of the two highest-numbered applied migrations and deletes their rows.

open as a page

In a Rails app, what is db/schema.rb, what writes it, and why do teams commit it instead of editing it by hand?

level: juniorimportance: must knowfreq 60%
basics
~20 s

db/schema.rb is Active Record's Ruby snapshot of the current database structure, rewritten from the live database after db:migrate and db:rollback. Teams commit it because new and test databases are built from it, and hand edits are overwritten at the next dump.

open as a page

In Rails, what is db/seeds.rb for, how do you load it, and why write it with find_or_create_by! instead of create!?

level: juniorimportance: must knowfreq 55%
basics
~20 s

db/seeds.rb is a Ruby file that creates the rows an app needs, such as countries and default plans, and bin/rails db:seed runs it. It may run many times, so find_or_create_by! makes reruns find existing rows instead of duplicating them.

open as a page

In a Rails 8.1 migration, how do you create a shipments table that belongs to couriers, and what does t.references :courier add?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Call create_table :shipments in the change method. Inside it, t.references :courier adds a bigint courier_id column and an index on it; a real foreign key constraint appears only with foreign_key: true, and NOT NULL only with null: false.

open as a page

In Rails 8.1, what do db:create, db:setup, db:reset and db:prepare each do, and which of them replays your migrations?

level: middleimportance: must knowfreq 55%
basics
~20 s

db:create makes empty databases; db:setup creates, loads the schema file and seeds; db:reset drops then runs setup; db:prepare sets up a missing database or runs pending migrations on an existing one. None replays all migrations; db:migrate:reset does.

open as a page

With the ViewComponent gem, what files make up a component, and how do you render one from a Rails view?

level: juniorimportance: must knowfreq 32%
basics
~10 s

A ViewComponent is a Ruby class inheriting from ViewComponent::Base, usually app/components/alert_component.rb, with a sidecar template beside it, alert_component.html.erb. A view renders it with render(AlertComponent.new(kind: :warning, message: "...")).

open as a page

In a Rails ERB template, how do <% %>, <%= %> and <%# %> differ, and what does <%= %> do to its value?

level: juniorimportance: must knowfreq 72%
basics
~20 s

In a Rails ERB template, <% %> runs Ruby without output, <%= %> runs it and appends the result to the page HTML-escaped unless it is html_safe, and <%# %> is a comment that never runs.

open as a page

In a Rails app, how does an action's view end up inside app/views/layouts/application.html.erb, and what does yield do there?

level: juniorimportance: must knowfreq 68%
basics
~10 s

In Rails, Action View renders the action's template first, then renders the controller's layout, by default layouts/<controller> or else layouts/application, and the layout's bare yield inserts the template's HTML at that point.

open as a page

In a Rails view, how do you render a partial such as _gig.html.erb and pass it data with locals:?

level: juniorimportance: must knowfreq 70%
basics
~20 s

In Rails, a partial is a template whose file name starts with an underscore, such as gigs/_gig.html.erb; render it with render partial: "gig", locals: { gig: @gig }, the shorthand render "gig", gig: @gig, or render @gig via to_partial_path.

open as a page

In a Rails controller, why does a failed save re-render the form with render :new, status: :unprocessable_content instead of redirecting?

level: juniorimportance: must knowfreq 70%
basics
~20 s

The errors and the typed input exist only on @volunteer in this request, so the action renders the form again from it. Status 422, :unprocessable_content, marks the failure, which Turbo Drive needs to display it.

open as a page

In a Rails form_with block, what HTML do f.label, f.text_field, f.email_field, f.textarea and f.hidden_field produce for a registration?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Each builder helper names its input registration[attribute], gives it the id registration_attribute, and fills it from the record. f.label points for= at that id and looks its text up through I18n, falling back to the attribute's human name.

open as a page

In a Rails 8.1 veterinary app, how can one _form partial built with form_with model: @pet serve both the new and the edit page?

level: juniorimportance: must knowfreq 78%
basics
~20 s

form_with model: reads the record: a new Pet posts to /pets, a saved one sends PATCH to /pets/7 because persisted? is true. Fields are named pet[...], prefilled from the record, and f.submit says Create Pet or Update Pet.

open as a page

Why does Rails' f.checkbox render a hidden input with value 0 before the checkbox, and how do you change or remove it?

level: middleimportance: must knowfreq 65%
basics
~20 s

Browsers omit unchecked checkboxes, so Rails writes a hidden input with the same name and value 0 first; when checked, the later 1 replaces it in params. Change it through checked and unchecked value arguments; remove it with include_hidden: false.

open as a page

Browsers submit forms only as GET or POST, so what HTML does Rails' form_with emit to reach a PATCH or DELETE route?

level: middleimportance: must knowfreq 60%
basics
~10 s

form_with keeps method="post" on the form tag and adds a hidden input named _method whose value is patch, put or delete. Rails' method-override middleware reads it, so routing sees the intended verb.

open as a page

In a Rails 8.1 app using jsbundling-rails, what is app/assets/builds for, and how does a TypeScript entry point end up served to the browser?

level: juniorimportance: must knowfreq 55%
basics
~20 s

app/assets/builds is the hand-off folder: the package.json build script that jsbundling-rails installs writes bundled files there, and Propshaft serves them like any other asset because every app/assets subfolder is on its load path. The folder holds build output only and is git-ignored.

open as a page

In a Rails 8.1 campsite-booking app on importmap-rails, what does bin/importmap pin flatpickr do to config/importmap.rb and vendor/javascript?

level: juniorimportance: must knowfreq 52%
basics
~20 s

bin/importmap pin asks the JSPM API to resolve the package and its dependencies, downloads each file into vendor/javascript, and writes a pin "flatpickr" # @version line into config/importmap.rb. At runtime the app serves those vendored files itself.

open as a page

In a Rails 8.1 app on importmap-rails, how do config/importmap.rb and javascript_importmap_tags let the browser run import statements with no Node build step?

level: juniorimportance: must knowfreq 58%
basics
~20 s

config/importmap.rb pins bare module names to files on the asset load path; javascript_importmap_tags renders those pins as a script type="importmap" block of digested URLs, adds modulepreload links and imports "application", so the browser resolves every import natively.

open as a page

In Rails 8.1, what does Propshaft do with the files on config.assets.paths, and which Sprockets jobs does it leave to other tools?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Propshaft gathers every file on config.assets.paths under one logical namespace, serves them in development, and on assets:precompile copies all of them into public/assets with a content digest in each name. It does no transpiling, bundling or minifying.

open as a page

In a Rails 8.1 app with jsbundling-rails and dartsass-rails, what do bin/dev and Procfile.dev run, and what goes wrong if you start only bin/rails server?

level: middleimportance: must knowfreq 47%
basics
~10 s

bin/dev runs foreman on Procfile.dev: the Rails server plus yarn build --watch and bin/rails dartsass:watch. With only bin/rails server nothing rebuilds app/assets/builds, so edits never appear and a fresh clone has no built files.

open as a page

In a Rails app, what is a model concern, where does it live, and how would you share soft-delete behaviour across several models with one?

level: juniorimportance: must knowfreq 62%
basics
~20 s

A concern is a module that extends ActiveSupport::Concern, kept in app/models/concerns (or app/controllers/concerns). Its included block declares scopes and callbacks on the host, class_methods adds class methods, and plain defs become instance methods; each model then writes include SoftDeletable.

open as a page

In Rails, how do Active Support's blank?, present? and presence differ from Ruby's nil? and empty?, and what does each return?

level: juniorimportance: must knowfreq 72%
basics
~20 s

blank? is true for nil, false, whitespace-only strings and empty collections; present? is its negation; presence returns the receiver when present and nil otherwise. Ruby's nil? only matches nil, and empty? does not exist on nil.

open as a page

In Rails, why should application code call Time.current and Date.current rather than Time.now and Date.today?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Time.now and Date.today use the server process's zone (ENV['TZ']); Time.current and Date.current use Time.zone, the app's configured or per-request zone. Mixing them shifts wall-clock times by the offset and, near midnight, gives a different date.

open as a page

In a Rails model, what does delegate :status, to: :rsvp, prefix: true, allow_nil: true generate, and what changes without allow_nil?

level: middleimportance: must knowfreq 52%
basics
~10 s

It defines rsvp_status, which calls rsvp.status and returns nil when rsvp is nil. Without allow_nil: a nil rsvp raises ActiveSupport::DelegationError, a NoMethodError subclass naming the method and the nil target.

open as a page

In Rails 8.1, when exactly are Current attributes reset, and what do the before_reset and resets hooks on a CurrentAttributes class run?

level: middleimportance: must knowfreq 42%
basics
~20 s

The Rails executor wraps each request and job; when it completes, CurrentAttributes.clear_all runs every instance's reset callbacks and discards the instances, so the next execution builds fresh ones from the defaults. before_reset runs before the values are cleared, resets after.

open as a page

In Rails 8, what does bin/rails generate authentication add to an app, and what does it deliberately leave out?

level: juniorimportance: must knowfreq 65%
basics
~10 s

It writes User, Session and Current models, SessionsController, PasswordsController, an Authentication concern included in ApplicationController, a reset mailer, migrations, routes, tests and bcrypt. It creates no sign-up: no generated action makes a new User.

open as a page

In CanCanCan, how does one Ability class let library patrons read the catalogue while librarians manage loans, and how is it checked?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Every rule lives in Ability#initialize(user) as can or cannot calls: can :read, Book for everyone, can :manage, Loan for librarians. Controllers and views check with can?, and authorize! raises CanCan::AccessDenied when the rule set refuses.

open as a page

With Devise 5, what do `devise_for :users` and `before_action :authenticate_user!` give a Rails controller, and what does a signed-out visitor get back?

level: juniorimportance: must knowfreq 78%
basics
~10 s

devise_for :users registers a :user mapping with its routes and defines authenticate_user!, user_signed_in?, current_user and user_session. A signed-out HTML or Turbo visitor is redirected to the sign-in page; a JSON request gets a 401.

open as a page

With the Doorkeeper gem, what do doorkeeper:install, use_doorkeeper and resource_owner_authenticator each contribute when a Rails app becomes an OAuth 2 provider?

level: juniorimportance: must knowfreq 30%
basics
~10 s

Doorkeeper's doorkeeper:install generator writes the initializer and adds use_doorkeeper, which draws /oauth/authorize, /oauth/token and the client screens; resource_owner_authenticator is the block that returns the signed-in user or redirects to sign-in.

open as a page

In a Rails app using OmniAuth 2, how does a Sign in with GitHub click travel from the button to your callback action?

level: juniorimportance: must knowfreq 50%
basics
~20 s

OmniAuth::Builder is Rack middleware. A POST to /auth/github runs the request phase and redirects to the provider; the provider sends the browser back to /auth/github/callback, where the middleware stores the result in request.env["omniauth.auth"] and passes the request to your routed action.

open as a page

In a Rails 8.1 app, how do you add a mapping-service API key to the encrypted credentials, and how does application code read it?

level: juniorimportance: must knowfreq 74%
basics
~10 s

Run bin/rails credentials:edit, which decrypts config/credentials.yml.enc with config/master.key into your editor and re-encrypts it on save. Code reads Rails.application.credentials.dig(:maps, :api_key), or the bang accessor to fail on a blank value.

open as a page

In a Rails 8.1 app whose ApplicationController never calls protect_from_forgery, what stops a forged POST, and where does the token come from?

level: juniorimportance: must knowfreq 72%
basics
~10 s

Rails' Action Controller railtie runs protect_from_forgery with: :exception on ActionController::Base because load_defaults sets default_protect_from_forgery. form_with and button_to embed a hidden authenticity_token, csrf_meta_tags exposes one for scripts, and a bad token raises InvalidAuthenticityToken.

open as a page

How do you set up Active Record Encryption in a Rails 8.1 app to encrypt a patient's national ID column, and what does the database store?

level: juniorimportance: must knowfreq 52%
basics
~10 s

Run bin/rails db:encryption:init, paste its primary_key, deterministic_key and key_derivation_salt under active_record_encryption in credentials, then declare encrypts :national_id. Rails stores a Base64 JSON envelope of ciphertext, IV and auth tag, and decrypts on read.

open as a page

In a Rails 8.1 app, what does config.force_ssl = true do to each request, and how does config.ssl_options adjust it?

level: juniorimportance: must knowfreq 55%
basics
~10 s

config.force_ssl inserts the ActionDispatch::SSL middleware, which redirects plain-HTTP requests to HTTPS, adds the Secure flag to cookies and sends Strict-Transport-Security; config.ssl_options tunes or switches off each of those three jobs.

open as a page

In an Active Record query, why is Car.where("make = '#{params[:make]}'") unsafe, and which forms of where pass values safely?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Ruby interpolates params[:make] into the string before Active Record sees it, and where treats a lone string as raw SQL, so a quote in the input rewrites the query; hash conditions, ? placeholders and :named binds quote the value instead.

open as a page

In a Rails 8.1 app, how do you pause a request inside a controller action or model method, and what does the generated Gemfile contribute?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Put debugger, or binding.break, on the line you want to inspect. The generated Gemfile loads the debug gem in development and test with require: "debug/prelude", so the call opens an rdbg prompt in the terminal running the server while the request waits.

open as a page

In a Rails app, what does Rails.error.report do with an exception you rescued, and what do its handled: and severity: options default to?

level: juniorimportance: must knowfreq 40%
basics
~10 s

Rails.error.report(error) hands an exception you already rescued to every registered error subscriber, then returns nil without re-raising it. handled: defaults to true, and severity: defaults to :warning when handled, :error when handled: false.

open as a page

In a Rails 8.1 app, which log level does each environment run at, and how do you change production's without a code change?

level: juniorimportance: must knowfreq 58%
basics
~10 s

Development and test log at debug, Rails' own default. The generated production.rb sets config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info"), so production runs at info until you set RAILS_LOG_LEVEL and restart.

open as a page

In a Rails 8.1 development log, what do verbose_query_logs and verbose_redirect_logs add, and why are they left off in production?

level: juniorimportance: must knowfreq 35%
basics
~20 s

Both add a ↳ line naming the line of your own code behind the entry: verbose_query_logs under each SQL statement, verbose_redirect_logs (new in 8.1) under each redirect. Each walks the call stack, so only development enables them.

open as a page

In Rails, how do Rails.error.handle and Rails.error.record differ in what they report, return and re-raise when the block fails?

level: middleimportance: must knowfreq 45%
basics
~20 s

Rails.error.handle reports a failure as handled with severity :warning, swallows it and returns nil or fallback.call. Rails.error.record reports it as unhandled with severity :error and re-raises it. Both return the block's value when nothing fails.

open as a page

In a Rails view, what does <% cache product do %> store, under which key, and what makes that fragment stop being served?

level: juniorimportance: must knowfreq 70%
basics
~20 s

The cache helper stores the HTML its block renders, keyed by the template path, a digest of the template and its partials, and the record's cache_key. A new cache_version (from updated_at) or a template edit makes Rails render it again.

open as a page

In a Rails controller, what does fresh_when(@article) put on the response, and what does Rails skip when the request is already fresh?

level: juniorimportance: must knowfreq 48%
basics
~20 s

fresh_when(@article) sets a weak ETag built from the record's cache key and version and a Last-Modified header from updated_at; if the request's If-None-Match or If-Modified-Since matches, Rails answers 304 Not Modified with no body and never renders the template.

open as a page

In Rails, what does Rails.cache.fetch do on a hit and on a miss, and how do expires_in: and expires_at: bound the entry?

level: juniorimportance: must knowfreq 65%
basics
~20 s

Rails.cache.fetch returns the stored value on a hit; on a miss it runs the block, writes the result under the key and returns it. expires_in: sets a duration from the write, expires_at: an absolute time; passing both raises ArgumentError.

open as a page

In a new Rails 8.1 app, which store does config.cache_store select in development, test and production, and why does each environment differ?

level: juniorimportance: must knowfreq 62%
basics
~20 s

A new Rails 8.1 app sets config.cache_store to :memory_store in development, :null_store in test and :solid_cache_store in production; Rails builds Rails.cache from that value at boot, and an app that sets nothing falls back to :file_store in tmp/cache/.

open as a page

In Rails Russian-doll caching, why can editing a review leave the outer product fragment stale, and what keeps the nested fragments fresh?

level: middleimportance: must knowfreq 60%
basics
~20 s

The outer fragment is versioned by the product's updated_at alone, so a review change leaves it valid and its block never reaches the fresh review fragment. Declaring belongs_to :product, touch: true on Review moves the outer version.

open as a page

In Rails, what is the difference between calling perform_later and perform_now on an Active Job class, and what does each one return?

level: juniorimportance: must knowfreq 78%
basics
~20 s

perform_later serializes the arguments and hands the job to the configured queue adapter, returning the job instance (or false if enqueuing failed); perform_now runs perform at once in the calling process and returns perform's own return value.

open as a page

In a new Rails 8.1 app, which Active Job backend runs jobs in production, where does it keep them, and what starts its workers?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Solid Queue: rails new installs it, stores jobs as rows in a separate queue database and sets it as the production adapter. bin/jobs starts its supervisor, or Puma starts it through plugin :solid_queue when SOLID_QUEUE_IN_PUMA is set.

open as a page

For a Rails job calling a flaky shipping-label API, which errors belong in retry_on, which in discard_on, and what do retry_on's defaults do?

level: middleimportance: must knowfreq 62%
basics
~20 s

retry_on takes transient errors such as timeouts and rate limits; discard_on takes errors a retry cannot fix, such as an invalid address. By default retry_on allows 5 attempts in total, about 3 seconds apart plus up to 15% jitter, then re-raises.

open as a page

In a Rails 8.1 app, what changes when Sidekiq runs jobs through Active Job's :sidekiq adapter rather than as native Sidekiq::Job classes?

level: middleimportance: must knowfreq 58%
basics
~10 s

With config.active_job.queue_adapter = :sidekiq, ApplicationJob classes keep perform_later, GlobalID arguments, callbacks and retry_on, and Sidekiq runs them inside a wrapper job. Native Sidekiq::Job classes skip Active Job: JSON-only arguments, Sidekiq's own API, less overhead.

open as a page

With Sidekiq 8 in a Rails app, how is a job whose perform raises retried, and when does it reach the dead set?

level: middleimportance: must knowfreq 60%
basics
~20 s

Sidekiq puts a failed job in its retry set and reruns it with growing delays, 25 times over about three weeks by default. When retries run out it moves the job to the dead set, which keeps 10,000 jobs for six months.

open as a page

In Rails Action Cable, how do stream_from and stream_for differ, and how does a server-side broadcast reach a channel's subscribers?

level: juniorimportance: must knowfreq 58%
basics
~10 s

stream_from subscribes a channel to a broadcasting by its literal string name; stream_for builds that name from a record (channel name plus GlobalID). ActionCable.server.broadcast(name, data) or SomeChannel.broadcast_to(record, data) publishes it to every current subscriber.

open as a page

When a Rails app's Action Cable runs on four app servers, which cable.yml adapters deliver every broadcast, and how do solid_cable, redis and postgresql differ?

level: middleimportance: must knowfreq 45%
basics
~20 s

Across four servers any shared adapter works, never async: solid_cable writes each broadcast as a row that every process polls for, redis publishes through a Redis server, and postgresql uses NOTIFY on the app's own database, with payloads capped near 8000 bytes.

open as a page

In a Rails Action Cable connection class, how do identified_by, connect and reject_unauthorized_connection authenticate each WebSocket?

level: middleimportance: must knowfreq 52%
basics
~20 s

ApplicationCable::Connection declares identified_by :current_user; its connect method runs once when the socket opens and sets current_user from a signed cookie, or calls reject_unauthorized_connection, which raises UnauthorizedError so Rails closes the socket with reason unauthorized and no reconnect.

open as a page

In a new Rails 8.1 app, which Action Cable adapter does config/cable.yml set for development, test and production, and why?

level: juniorimportance: should knowfreq 40%
basics
~20 s

A new Rails 8.1 app's config/cable.yml uses async in development, test in test and solid_cable in production, connected to a separate cable database. rails new runs solid_cable:install, which overwrites Rails' own template whose production entry was redis.

open as a page

In a Rails app, how does a createConsumer subscription's perform call from @rails/actioncable reach a method on an Action Cable channel?

level: middleimportance: should knowfreq 42%
basics
~10 s

createConsumer() from @rails/actioncable opens one WebSocket (to the action-cable-url meta tag or /cable); consumer.subscriptions.create({channel: "TicketChatChannel", ticket_id: 42}, callbacks) subscribes; subscription.perform("speak", {body}) calls the channel's public speak(data) method.

open as a page

In Rails Action Mailer, what is the difference between deliver_now and deliver_later, and where does the mailer action actually run?

level: juniorimportance: must knowfreq 74%
basics
~10 s

deliver_now runs the mailer action, renders and sends the email in the current process. deliver_later enqueues ActionMailer::MailDeliveryJob with the mailer name, action and arguments, and the worker runs the action and sends it later.

open as a page

In Rails 8.1, what does bin/rails generate mailer Order confirmation create, and how do mail() and its templates build the email?

level: juniorimportance: must knowfreq 62%
basics
~20 s

The generator writes OrderMailer with a confirmation action, text and HTML views under app/views/order_mailer, a test and a preview. Calling mail(to:, subject:) merges the class defaults, renders every confirmation template inside the mailer layout and returns a multipart message.

open as a page

In Rails Action Mailbox, how do routing rules in ApplicationMailbox match an inbound email, and what happens when none match?

level: middleimportance: should knowfreq 24%
basics
~20 s

ApplicationMailbox's routing rules map an address matcher to a mailbox name, and the first rule that matches wins. Strings and regexps are compared with every recipient; with no match the email is marked bounced and ActionMailbox::Router::RoutingError is raised.

open as a page

In Rails Action Mailbox, what happens to an inbound email between the ingress request and a mailbox's process method?

level: middleimportance: should knowfreq 28%
basics
~20 s

The configured ingress controller saves the raw message as an InboundEmail with status pending and answers at once. A RoutingJob then asks ApplicationMailbox for the first matching route and runs that mailbox's callbacks and process, updating the status.

open as a page

In Rails 8.1, how do you add an Action Text rich-text field to a model, and where is its content stored?

level: juniorimportance: must knowfreq 52%
basics
~20 s

Run bin/rails action_text:install and migrate, declare has_rich_text :notes on the model, and use form.rich_textarea :notes in the form. The HTML is stored in a row of action_text_rich_texts linked polymorphically to the record, not in the model's table.

open as a page

In a Rails model, what does has_one_attached :avatar set up, and which tables hold the uploaded file's data?

level: juniorimportance: must knowfreq 72%
basics
~20 s

has_one_attached :avatar adds no column; it defines an avatar_attachment association to a polymorphic row in active_storage_attachments, which points at a row in active_storage_blobs describing the file. The bytes themselves live in the configured storage service.

open as a page

In a Rails 8.1 app, what does config/storage.yml declare, and how does each environment choose its Active Storage service?

level: juniorimportance: must knowfreq 60%
basics
~20 s

config/storage.yml names storage services, each with an adapter (Disk, S3, GCS or Mirror) and its settings. Each config/environments file sets config.active_storage.service to one of those names, and every blob records the service it was stored on.

open as a page

When a teacher drops an image into an Action Text Trix editor, how is the file uploaded, referenced in the HTML and rendered later?

level: middleimportance: must knowfreq 40%
basics
~20 s

Action Text's JavaScript direct-uploads the file to Active Storage when it is dropped, and the body stores an action-text-attachment tag with the blob's signed global id. Saving attaches the blob as an embed; rendering draws the blob partial.

open as a page

In Active Storage, how is a named variant such as :thumb on has_one_attached generated, stored and reused?

level: middleimportance: must knowfreq 56%
basics
~20 s

A named variant is declared in has_one_attached's block with attachable.variant. Active Storage transforms the original with image_processing on first use, stores the result as its own blob, and records it in active_storage_variant_records so later requests reuse it.

open as a page

In a Rails view, what does t('.title') look up, and where do the translations it reads come from?

level: juniorimportance: must knowfreq 68%
basics
~10 s

A leading dot makes the view helper t scope the key by the current template: t('.title') in app/views/campsites/index.html.erb reads campsites.index.title from YAML or Ruby files loaded automatically from config/locales by the Simple backend.

open as a page

In a Rails controller, how do you set each request's locale from params[:locale] or a (:locale) route scope, and why use I18n.with_locale in an around_action?

level: middleimportance: must knowfreq 62%
basics
~10 s

Add around_action :switch_locale to ApplicationController, take params[:locale] (filled by ?locale= or a (:locale) path scope) when I18n.locale_available? accepts it, else default_locale, and run I18n.with_locale(locale, &action), which restores the previous locale afterwards.

open as a page

With Rails I18n, how does t('campsites.show.nights', count: n) pick between one and other keys, and what goes wrong for French?

level: middleimportance: must knowfreq 55%
basics
~20 s

Passing count: makes I18n pick a subkey and interpolate %{count}. The default Simple backend applies only the English rule (1 is one, everything else other, zero if present), so French singular zero needs the Pluralization module and a fr plural rule.

open as a page

In a Rails app, what do config.i18n.default_locale and config.i18n.available_locales control, and what happens when code asks for an unlisted locale?

level: juniorimportance: should knowfreq 45%
basics
~20 s

default_locale (:en unless configured) is what I18n.locale returns until something sets it; available_locales is the allow list, derived from loaded translation data when unset. Since enforce_available_locales defaults to true, using an unlisted locale raises I18n::InvalidLocale.

open as a page

In a Rails app, which locale keys translate an Active Record model's name and its attribute names, and which helpers read them?

level: juniorimportance: should knowfreq 42%
basics
~10 s

Model names live under activerecord.models.campsite (one/other) and attribute names under activerecord.attributes.campsite.nightly_price. Campsite.model_name.human, Campsite.human_attribute_name, form labels, submit buttons and error full messages read them, falling back to humanized names.

open as a page

In a Rails app using Kaminari, how do you paginate job listings with page and per, and render the page links in the view?

level: juniorimportance: must knowfreq 46%
basics
~20 s

Call Listing.order(posted_at: :desc).page(params[:page]).per(20) in the controller and <%= paginate @listings %> in the view. Kaminari adds page to every Active Record model, per exists only on that page scope, and the default size is 25.

open as a page

With Pagy 43 in Rails 8.1, how do you paginate an admin product list in the controller and render its page links?

level: juniorimportance: must knowfreq 50%
basics
~10 s

Include Pagy::Method in ApplicationController, assign @pagy, @products = pagy(:offset, Product.order(:name)) in the action, and print <%== @pagy.series_nav %> in the view; Pagy 43 helpers are methods on @pagy that return HTML strings.

open as a page

On a Kaminari-paginated job board with a per-page selector, how do you stop ?per=100000 loading the whole table, and where can the cap live?

level: middleimportance: should knowfreq 34%
basics
~10 s

Kaminari applies no cap by default, so per(params[:per]) passes any number to LIMIT. Set max_paginates_per 100 on the model, config.max_per_page in Kaminari.configure, or per(n, max_per_page: 100); larger requests are silently clamped.

open as a page

With Kaminari, what does without_count change about the queries Listing.page(n) runs, and which view helpers stop working with it?

level: middleimportance: should knowfreq 30%
basics
~10 s

without_count drops the COUNT query: Kaminari loads limit + 1 rows to tell whether a next page exists. total_count then raises, so paginate and page_entries_info fail; link_to_prev_page and link_to_next_page still work.

open as a page

In a Rails API controller using Pagy 43, how do headers_hash, data_hash and client_limit expose pagination metadata and let a client choose its page size?

level: middleimportance: should knowfreq 28%
basics
~10 s

@pagy.headers_hash returns a link header plus current-page, page-limit, total-count and total-pages to merge into response.headers; @pagy.data_hash returns selected numbers and URLs for a JSON body; client_limit: caps a ?limit= request.

open as a page

With factory_bot, how do build, create, build_stubbed and attributes_for differ, and which of them write to the database?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Only create writes: it builds the object and calls save!. build returns an unsaved instance, build_stubbed an unsaved one that pretends to be persisted with a fake id, and attributes_for a plain hash without associations.

open as a page

In a Rails app, how are YAML fixtures in test/fixtures loaded into the test database, and what does teams(:riverside) return inside a test?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Each test/fixtures/*.yml file holds labelled rows for one table; fixtures :all in test_helper.rb inserts them before the tests run, and teams(:riverside) returns the Team record with that label, loaded from the database.

open as a page

In a Rails test, what does assert_difference check, and how do you assert that a sign-up creates one User and one Session?

level: juniorimportance: must knowfreq 58%
basics
~20 s

assert_difference evaluates an expression, runs the block, evaluates it again and asserts the change equals the expected difference, 1 by default. A hash checks several counts: assert_difference({ "User.count" => 1, "Session.count" => 1 }) { post sign_up_path, params: ... }.

open as a page

In a Rails 8.1 app, how do you add and run a system test, and what does ApplicationSystemTestCase with driven_by set up?

level: juniorimportance: must knowfreq 56%
basics
~10 s

A system test subclasses ApplicationSystemTestCase, which inherits ActionDispatch::SystemTestCase and calls driven_by :selenium, using: :headless_chrome. bin/rails generate system_test creates both files in Rails 8.1, and bin/rails test:system runs them; plain bin/rails test skips them.

open as a page

In a Rails 8.1 app, when do you subclass ActiveSupport::TestCase, ActionDispatch::IntegrationTest or ActionController::TestCase, and what does each exercise?

level: juniorimportance: must knowfreq 68%
basics
~20 s

ActiveSupport::TestCase is the base for model and plain-Ruby tests; ActionDispatch::IntegrationTest sends requests through routing, middleware, controller and view, and is what Rails generates for controller tests; ActionController::TestCase dispatches one action directly and is the legacy style.

open as a page

In Rails 8.1, what is a Rails engine, and how does `rails plugin new --mountable` differ from `--full`?

level: juniorimportance: must knowfreq 42%
basics
~20 s

A Rails engine is a gem whose Rails::Engine subclass adds app/ code, routes, migrations and config to a host app. --full blends into the host's namespace and routes; --mountable adds isolate_namespace and its own route set, mounted at a path.

open as a page

In a Rails engine, what does `isolate_namespace Billing` change for its tables, helpers, routes and model naming?

level: middleimportance: must knowfreq 40%
basics
~20 s

isolate_namespace Billing prefixes the engine's tables with billing_, routes its routes to Billing:: controllers, gives its controllers only Billing's helpers and route helpers, strips the namespace from param and route keys, and names the engine billing.

open as a page

In a Ruby gem, what is a `Rails::Railtie` for, and what can an audit-trail gem's railtie register with the host Rails app?

level: middleimportance: must knowfreq 30%
basics
~20 s

A Rails::Railtie subclass is how a gem joins a host app's boot. Its class body can add initializers, a config namespace, middleware, rake tasks, generators and console, runner or server blocks; app/ code, routes and migrations need an engine.

open as a page

Why is `ActiveRecord::Base.include(AuditTrail::Model)` in a gem's railtie initializer harmful, and how do you find which gem loads Active Record early?

level: seniorimportance: must knowfreq 26%
basics
~20 s

Referencing ActiveRecord::Base during boot loads Active Record early, slowing every boot and running its load hooks before the app's config/initializers, so class-level config.active_record values set there are never copied. Use ActiveSupport.on_load(:active_record) and trace the loader.

open as a page

In a Rails 8.1 app's config/application.rb, what does `require "rails/all"` load, and how is a framework such as Action Cable left out?

level: juniorimportance: should knowfreq 30%
basics
~10 s

require "rails/all" requires each framework's railtie or engine, such as active_record/railtie and action_cable/engine, which registers its initializers and config namespace. An app without Action Cable requires frameworks one by one, leaving "action_cable/engine" commented out.

open as a page

In the Dockerfile that Rails 8.1's `rails new` generates, what do the base, build and final stages each do, and what ends up in the image you run?

level: juniorimportance: must knowfreq 58%
basics
~20 s

The base stage sets RAILS_ENV=production, the Bundler variables and runtime packages; the build stage adds compilers, installs gems and precompiles assets; the final stage restarts from base, copies only gems and app, and runs as UID 1000.

open as a page

In a Rails 8.1 app, what does the generated `/up` route do, and what does a 200 from `Rails::HealthController` actually prove to a load balancer?

level: juniorimportance: must knowfreq 52%
basics
~20 s

/up routes to Rails::HealthController#show, which answers 200 with a green page, or JSON status: "up", once the app has booted and can serve a request. It does not check the database, cache or job queue.

open as a page

In a new Rails 8.1 app, what does the generated config/puma.rb set up, and what does it leave to Puma's own defaults?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Rails 8.1's config/puma.rb sets threads per process from RAILS_MAX_THREADS (default 3), the port from PORT (default 3000), and loads plugin :tmp_restart. It has no workers line, so Puma reads WEB_CONCURRENCY itself and otherwise runs one process.

open as a page

What does Thruster add in front of Puma in a Rails 8.1 container, and how do the Dockerfile's `EXPOSE 80` and Puma's port 3000 fit together?

level: middleimportance: must knowfreq 45%
basics
~20 s

Thruster is a small Go proxy the Dockerfile runs as ./bin/thrust ./bin/rails server: it starts Puma on PORT 3000, listens on port 80 itself, and adds gzip, caching of public responses, X-Sendfile, HTTP/2 and optional Let's Encrypt TLS.

open as a page

A ticket-resale Rails 8.1 app on a 4-core server, running the generated config/puma.rb, keeps one core busy; why, and what do you change?

level: middleimportance: must knowfreq 60%
basics
~20 s

With WEB_CONCURRENCY unset, Puma runs a single process, and its 3 threads take turns running Ruby under the GVL, so roughly one core works. Setting WEB_CONCURRENCY=4 (or auto) forks four workers, each with its own threads.

open as a page