Ruby on Rails
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 pageshowhide
guide
overview
~2 minRuby 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.
- Project Anatomy & Startup →
How an app is generated, laid out, named and booted; every other section assumes these conventions.
- Active Record Models →
Models, save paths, validations and callbacks: the layer most Rails code and most questions lean on.
- Query Interface →
Predicting the SQL and query count behind a relation, including eager loading and the N+1 problem.
- Route Mapping DSL →
How URLs and verbs map to controller actions through resourceful routes and path helpers.
- Action Controller Layer →
What an action does with a request: parameters, filters, rendering, sessions and error handling.
- 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_columnorupdate_allfor 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
wherestring 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
updateinside 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.noworDate.todayin 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
- Q-49561In 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%
- Q-50058In 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%
- Project Anatomy & Startup36 questions
- New App Options6 questions
- Default Directory Tree5 questions
- Doctrine & Naming Rules6 questions
- Middleware Stack & Dispatch4 questions
- Initializers & Load Order5 questions
- Autoloading & Reloading5 questions
- Upgrade Path & Defaults5 questions
- Command Line Toolkit14 questions
- Built-In Subcommands5 questions
- Generators & Destroy4 questions
- Custom Rake & Thor Tasks5 questions
- Route Mapping DSL27 questions
- Resources & Seven Actions5 questions
- Nested & Shallow Resources4 questions
- Member, Collection & Namespaces5 questions
- Constraints & Redirects4 questions
- Path Helpers & Polymorphism5 questions
- Listing & Match Order4 questions
- Action Controller Layer38 questions
- Formats & Implicit Rendering5 questions
- Strong Parameters5 questions
- Filter Chains & Halting4 questions
- Render, Redirect & Head6 questions
- Flash Messages & Session Stores4 questions
- Signed & Encrypted Cookies4 questions
- File Sends & Live Streams5 questions
- Rescue Handlers & Error Pages5 questions
- API-Only Apps12 questions
- Trimmed Middleware & CORS6 questions
- JSON Rendering & Jbuilder6 questions
- Active Record Models29 questions
- Table & Attribute Mapping6 questions
- Create, Update & Destroy6 questions
- Validators & Error Objects6 questions
- Lifecycle Callbacks5 questions
- Enums, Stores & Normalizers6 questions
- Model Associations21 questions
- Relation Types & Polymorphism5 questions
- Dependent, Inverse & Counters6 questions
- STI & Delegated Types5 questions
- Nested Attributes Writes5 questions
- Query Interface41 questions
- Filtering Conditions6 questions
- Ordering, Plucking & Limits5 questions
- Joins & Relation Merging5 questions
- Calculations & Grouping5 questions
- Named Scopes & Laziness5 questions
- Raw SQL & Sanitizing5 questions
- Eager Loading & N+15 questions
- Batches & Bulk Inserts5 questions
- Database Adapters29 questions
- SQLite in Production6 questions
- PostgreSQL-Specific Types6 questions
- MySQL & Trilogy5 questions
- Connections & Replicas6 questions
- Rollbacks, Savepoints & Locks6 questions
- Migration Files & Tasks26 questions
- Table & Column Changes5 questions
- Migrate & Rollback Commands5 questions
- Dump Formats & Versions5 questions
- Lock-Safe Changes6 questions
- Seed Data5 questions
- Action View Templates25 questions
- ERB Escaping & Lookup6 questions
- Layouts & Content Blocks4 questions
- Partials & Strict Locals4 questions
- Tag & Link Helpers6 questions
- ViewComponent & Phlex5 questions
- Form Builders20 questions
- Model vs URL Targets5 questions
- Field & Select Helpers5 questions
- Child Record Fields5 questions
- Error Display & Status5 questions
- Front-End Asset Builds15 questions
- Propshaft Digests5 questions
- Import Maps & Pins5 questions
- JS & CSS Bundling Gems5 questions
- Active Support28 questions
- Core Class Additions6 questions
- Concerns & Class Methods5 questions
- CurrentAttributes State5 questions
- Time Zones & TimeWithZone6 questions
- Notifications & Events6 questions
- Logins & Permissions38 questions
- Devise6 questions
- Pundit6 questions
- CanCanCan5 questions
- Built-In Generator6 questions
- OmniAuth Strategies5 questions
- Doorkeeper OAuth Provider5 questions
- API Tokens & HTTP Auth5 questions
- Hardening & Secrets32 questions
- Forgery Protection5 questions
- Credentials & Master Key5 questions
- Column-Level Encryption5 questions
- CSP, SSL & Host Rules6 questions
- Injection & Brakeman Scans6 questions
- Per-Action Throttling5 questions
- Logs, Errors & Debuggers21 questions
- Logger Levels & Tags5 questions
- Breakpoints & In-Page Console5 questions
- Reporter API & Subscribers6 questions
- Query Tags & Tracing5 questions
- Response & Data Caching24 questions
- Fragment & Russian-Doll6 questions
- Fetch, Expiry & Keys6 questions
- Store Backends & Defaults6 questions
- Conditional GET & ETags6 questions
- Active Job23 questions
- Enqueue, Perform & Continuations6 questions
- Solid Queue Workers6 questions
- Sidekiq Adapter6 questions
- Retries & Discards5 questions
- Action Cable10 questions
- Connections, Channels & Broadcasts5 questions
- Pub/Sub Backends & Origins5 questions
- Mailer & Mailbox12 questions
- Outbound Email Delivery6 questions
- Inbound Email Routing6 questions
- File Uploads & Rich Text18 questions
- Attachments & Variants6 questions
- Storage Services & Delivery6 questions
- Editor Content & Embeds6 questions
- I18n Translations12 questions
- Locale Files & Lookups6 questions
- Per-Request Locale Choice6 questions
- Page-Splitting Gems10 questions
- Pagy Series & Helpers5 questions
- Kaminari Scopes & Themes5 questions
- Testing Setup & Styles30 questions
- Test Types & Runner5 questions
- YAML Fixtures4 questions
- Factories & Traits5 questions
- Spec Types & Matchers5 questions
- System Tests & Capybara5 questions
- Job, Mail & Time Helpers6 questions
- Plugins & Engines11 questions
- Mounting & Namespace Isolation6 questions
- Railties & Load Hooks5 questions
- Deploying & Running19 questions
- Dockerfile & Thruster5 questions
- Environment Settings & Health5 questions
- Puma Concurrency Settings4 questions
- Load Time & Memory Footprint5 questions
questions
621 · 27 sectionsIn a Rails 8.1 app, why does an edited model take effect without a restart in development but not in production?
basics
~20 sDevelopment 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.
In a Rails 8.1 app, what do config/boot.rb, config/application.rb and config/environment.rb each do at startup?
basics
~10 sconfig/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.
What do convention over configuration and DRY mean in Rails, and which configuration does a Rails CRUD for people never write because of them?
basics
~20 sIn 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.
In a Rails genealogy app, which names does a Person model imply for its table, files, controller, routes, views and foreign keys?
basics
~10 sA 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.
In a Rails 8.1 app, what does each folder under app/ hold, and which base classes does rails new put there?
basics
~20 sRails 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.
In a Rails 8.1 app, what do bin/rails server, console, dbconsole and runner each start, and when do you reach for each?
basics
~20 sbin/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.
In a Rails 8.1 app, where do custom Rake tasks live, and what does bin/rails generate task loyalty recompute write?
basics
~20 sCustom 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.
In Rails 8.1, what do bin/rails generate model, controller, resource and scaffold each write, and when do you pick resource over scaffold?
basics
~20 smodel 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.
In Rails 8.1, how do RAILS_ENV and the -e flag decide which environment bin/rails console, runner and server boot into?
basics
~20 sWithout 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.
In a Rails 8.1 Rake task, what does the :environment prerequisite actually load, and what changes when the task also takes arguments?
basics
~20 sThe 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]".
In Rails, what is the difference between a named route's _path and _url helpers, and when do you need the _url form?
basics
~10 sBoth 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.
In Rails, how do you list an app's routes with bin/rails routes, and what do its -c, -g and --expanded options do?
basics
~20 sbin/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.
In config/routes.rb, which routes, helper names and params does resources :episodes nested inside resources :shows produce?
basics
~10 sNesting 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.
In config/routes.rb, which seven routes does resources :photos generate, with their HTTP verbs, paths, controller actions and named helpers?
basics
~10 sresources :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.
In config/routes.rb, how do you restrict a :year segment to four digits, and why does Rails reject ^ or \A in that regex?
basics
~20 sGive 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.
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?
basics
~10 sAn 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.
In a Rails controller, what does before_action :set_bouquet, only: %i[show edit update destroy] do, and why do scaffolds generate it?
basics
~20 sIt 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.
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?
basics
~10 sTrack.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.
In a Rails controller, what happens if you pass params[:job_application] straight to JobApplication.new, and how do strong parameters fix it?
basics
~10 sparams[: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.
In a Rails controller, how does render :show differ from redirect_to @ticket at the end of a ticket update action?
basics
~20 srender :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.
In Rails 8.1, what does generating an app with rails new --api change compared with a default rails new app?
basics
~10 srails 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.
In a Rails controller, what does render json: @flights do, and how do only:, except:, methods: and include: shape the output?
basics
~10 srender 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.
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?
basics
~20 sUncomment 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.
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?
basics
~10 srender 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.
In Rails 8.1, which ActionController::Base features does ActionController::API leave out, and how do you add one back?
basics
~10 sActionController::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.
In an Active Record model, in what order do the lifecycle callbacks run when save is called on a new record?
basics
~10 sSaving 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.
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?
basics
~20 sActive 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.
In Active Record, what do save, create and update return when a record is invalid, and how do save!, create! and update! differ?
basics
~10 ssave 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.
In a Rails 8.1 Order model, what does enum :status, { placed: 0, baking: 1, out_for_delivery: 2, delivered: 3 } give you?
basics
~20 sAn 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.
In an Active Record model, when do validations run, and how does a failed validation stop a save and report why?
basics
~20 ssave, 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.
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?
basics
~10 saccepts_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.
In an Active Record has_many, what do dependent: :destroy, :delete_all, :nullify and :restrict_with_error each do when the owner is destroyed?
basics
~20 sdependent: :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.
In an Active Record model, how do belongs_to, has_one and has_many differ, and which table holds the foreign key for each?
basics
~20 sbelongs_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.
In Active Record single-table inheritance, what does the type column store, and how does it shape queries and loaded objects?
basics
~20 sActive 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.
In an Active Record belongs_to, what do counter_cache: true and touch: true keep in sync on the parent, and what bypasses them?
basics
~20 scounter_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.
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?
basics
~20 sMember.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.
In Active Record, what SQL does where generate when a hash condition's value is nil, an array, or a Ruby range?
basics
~20 sThe 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.
In Active Record, which queries does Order.includes(:customer, line_items: :wine) run for an orders page printing customers, items and wines?
basics
~20 sWith 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.
In Active Record, what SQL do joins and left_joins generate from association names, and how do you filter on the joined table?
basics
~20 sjoins(: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 }).
In Active Record, when does Article.published.featured.order(:published_at) actually query the database, and what do load, loaded? and reset do?
basics
~20 sBuilding 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.
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?
basics
~20 sconfig/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.
In a Rails 8.1 app on MySQL, why does database.yml set encoding: utf8mb4, and what does adding collation: change?
basics
~20 sutf8mb4 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.
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?
basics
~20 sAdd 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.
In a new Rails 8.1 app on SQLite, where do the database files live, and why must that directory survive every deploy?
basics
~20 sSQLite 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.
In Active Record, what does wrapping two wallet updates in a transaction block guarantee, and which failures inside the block actually roll it back?
basics
~20 sA 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.
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?
basics
~20 sdb: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.
In a Rails app, what is db/schema.rb, what writes it, and why do teams commit it instead of editing it by hand?
basics
~20 sdb/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.
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!?
basics
~20 sdb/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.
In a Rails 8.1 migration, how do you create a shipments table that belongs to couriers, and what does t.references :courier add?
basics
~20 sCall 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.
In Rails 8.1, what do db:create, db:setup, db:reset and db:prepare each do, and which of them replays your migrations?
basics
~20 sdb: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.
With the ViewComponent gem, what files make up a component, and how do you render one from a Rails view?
basics
~10 sA 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: "...")).
In a Rails ERB template, how do <% %>, <%= %> and <%# %> differ, and what does <%= %> do to its value?
basics
~20 sIn 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.
In a Rails 8.1 view, why should a Delete control for a record be built with button_to rather than link_to?
basics
~20 slink_to renders an <a> tag, and following a link is a GET, so it cannot safely or correctly reach destroy. button_to renders a small POST form with a hidden _method=delete field and a CSRF token, which Rails routes to destroy.
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?
basics
~10 sIn 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.
In a Rails view, how do you render a partial such as _gig.html.erb and pass it data with locals:?
basics
~20 sIn 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.
In a Rails controller, why does a failed save re-render the form with render :new, status: :unprocessable_content instead of redirecting?
basics
~20 sThe 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.
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?
basics
~20 sEach 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.
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?
basics
~20 sform_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.
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?
basics
~20 sapp/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.
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?
basics
~20 sbin/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.
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?
basics
~20 sconfig/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.
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?
basics
~20 sPropshaft 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.
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?
basics
~10 sbin/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.
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?
basics
~20 sA 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.
In Rails, how do Active Support's blank?, present? and presence differ from Ruby's nil? and empty?, and what does each return?
basics
~20 sblank? 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.
In Rails, why should application code call Time.current and Date.current rather than Time.now and Date.today?
basics
~20 sTime.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.
In a Rails model, what does delegate :status, to: :rsvp, prefix: true, allow_nil: true generate, and what changes without allow_nil?
basics
~10 sIt 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.
In Rails 8.1, when exactly are Current attributes reset, and what do the before_reset and resets hooks on a CurrentAttributes class run?
basics
~20 sThe 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.
In Rails 8, what does bin/rails generate authentication add to an app, and what does it deliberately leave out?
basics
~10 sIt 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.
In CanCanCan, how does one Ability class let library patrons read the catalogue while librarians manage loans, and how is it checked?
basics
~20 sEvery 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.
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?
basics
~10 sdevise_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.
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?
basics
~10 sDoorkeeper'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.
In a Rails app using OmniAuth 2, how does a Sign in with GitHub click travel from the button to your callback action?
basics
~20 sOmniAuth::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.
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?
basics
~10 sRun 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.
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?
basics
~10 sRails' 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.
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?
basics
~10 sRun 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.
In a Rails 8.1 app, what does config.force_ssl = true do to each request, and how does config.ssl_options adjust it?
basics
~10 sconfig.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.
In an Active Record query, why is Car.where("make = '#{params[:make]}'") unsafe, and which forms of where pass values safely?
basics
~20 sRuby 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.
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?
basics
~20 sPut 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.
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?
basics
~10 sRails.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.
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?
basics
~10 sDevelopment 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.
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?
basics
~20 sBoth 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.
In Rails, how do Rails.error.handle and Rails.error.record differ in what they report, return and re-raise when the block fails?
basics
~20 sRails.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.
In a Rails view, what does <% cache product do %> store, under which key, and what makes that fragment stop being served?
basics
~20 sThe 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.
In a Rails controller, what does fresh_when(@article) put on the response, and what does Rails skip when the request is already fresh?
basics
~20 sfresh_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.
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?
basics
~20 sRails.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.
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?
basics
~20 sA 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/.
In Rails Russian-doll caching, why can editing a review leave the outer product fragment stale, and what keeps the nested fragments fresh?
basics
~20 sThe 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.
In Rails, what is the difference between calling perform_later and perform_now on an Active Job class, and what does each one return?
basics
~20 sperform_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.
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?
basics
~20 sSolid 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.
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?
basics
~20 sretry_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.
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?
basics
~10 sWith 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.
With Sidekiq 8 in a Rails app, how is a job whose perform raises retried, and when does it reach the dead set?
basics
~20 sSidekiq 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.
In Rails Action Cable, how do stream_from and stream_for differ, and how does a server-side broadcast reach a channel's subscribers?
basics
~10 sstream_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.
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?
basics
~20 sAcross 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.
In a Rails Action Cable connection class, how do identified_by, connect and reject_unauthorized_connection authenticate each WebSocket?
basics
~20 sApplicationCable::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.
In a new Rails 8.1 app, which Action Cable adapter does config/cable.yml set for development, test and production, and why?
basics
~20 sA 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.
In a Rails app, how does a createConsumer subscription's perform call from @rails/actioncable reach a method on an Action Cable channel?
basics
~10 screateConsumer() 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.
In Rails Action Mailer, what is the difference between deliver_now and deliver_later, and where does the mailer action actually run?
basics
~10 sdeliver_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.
In Rails 8.1, what does bin/rails generate mailer Order confirmation create, and how do mail() and its templates build the email?
basics
~20 sThe 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.
Why does a link in a Rails mailer template need config.action_mailer.default_url_options, and what does a new Rails 8.1 app set it to?
basics
~20 sA mailer runs without an HTTP request, so URL helpers have no host to build absolute links from; default_url_options supplies it. A new 8.1 app sets localhost:3000 in development and the placeholder example.com in test and production.
In Rails Action Mailbox, how do routing rules in ApplicationMailbox match an inbound email, and what happens when none match?
basics
~20 sApplicationMailbox'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.
In Rails Action Mailbox, what happens to an inbound email between the ingress request and a mailbox's process method?
basics
~20 sThe 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.
In Rails 8.1, how do you add an Action Text rich-text field to a model, and where is its content stored?
basics
~20 sRun 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.
In a Rails model, what does has_one_attached :avatar set up, and which tables hold the uploaded file's data?
basics
~20 shas_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.
In a Rails 8.1 app, what does config/storage.yml declare, and how does each environment choose its Active Storage service?
basics
~20 sconfig/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.
When a teacher drops an image into an Action Text Trix editor, how is the file uploaded, referenced in the HTML and rendered later?
basics
~20 sAction 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.
In Active Storage, how is a named variant such as :thumb on has_one_attached generated, stored and reused?
basics
~20 sA 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.
In a Rails view, what does t('.title') look up, and where do the translations it reads come from?
basics
~10 sA 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.
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?
basics
~10 sAdd 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.
With Rails I18n, how does t('campsites.show.nights', count: n) pick between one and other keys, and what goes wrong for French?
basics
~20 sPassing 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.
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?
basics
~20 sdefault_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.
In a Rails app, which locale keys translate an Active Record model's name and its attribute names, and which helpers read them?
basics
~10 sModel 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.
In a Rails app using Kaminari, how do you paginate job listings with page and per, and render the page links in the view?
basics
~20 sCall 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.
With Pagy 43 in Rails 8.1, how do you paginate an admin product list in the controller and render its page links?
basics
~10 sInclude 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.
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?
basics
~10 sKaminari 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.
With Kaminari, what does without_count change about the queries Listing.page(n) runs, and which view helpers stop working with it?
basics
~10 swithout_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.
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?
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.
With factory_bot, how do build, create, build_stubbed and attributes_for differ, and which of them write to the database?
basics
~20 sOnly 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.
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?
basics
~10 sEach 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.
In a Rails test, what does assert_difference check, and how do you assert that a sign-up creates one User and one Session?
basics
~20 sassert_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: ... }.
In a Rails 8.1 app, how do you add and run a system test, and what does ApplicationSystemTestCase with driven_by set up?
basics
~10 sA 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.
In a Rails 8.1 app, when do you subclass ActiveSupport::TestCase, ActionDispatch::IntegrationTest or ActionController::TestCase, and what does each exercise?
basics
~20 sActiveSupport::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.
In Rails 8.1, what is a Rails engine, and how does `rails plugin new --mountable` differ from `--full`?
basics
~20 sA 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.
In a Rails engine, what does `isolate_namespace Billing` change for its tables, helpers, routes and model naming?
basics
~20 sisolate_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.
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?
basics
~20 sA 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.
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?
basics
~20 sReferencing 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.
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?
basics
~10 srequire "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.
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?
basics
~20 sThe 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.
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?
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.
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?
basics
~20 sRails 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.
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?
basics
~20 sThruster 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.
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?
basics
~20 sWith 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.