NEGABARO Rails
An encyclopedia of essential concepts for Rails development.
Foundation
What Is MVC? How Rails Splits Model, View and Controller
Follow one request and you can tell where each piece of code belongs
Follow one Rails request through the router, controller, model and view in the order they really run. You will be able to decide where code belongs and explain why SQL shows up during view rendering.
Convention over Configuration: Why Naming Alone Wires Up Rails
The naming map: Post → posts table → PostsController
Philosophy where following naming conventions lets Rails auto-connect everything. e.g., Post model → posts table → PostsController → app/views/posts/
Rails Directory Structure: What Goes in app/, config/ and db/
A walk through the folders rails new creates
Rails project directory structure physically reflects MVC. Each folder (app/, config/, db/, test/) has a clearly defined role.
What Is Rack? How Middleware Wraps Every Rails Request
The call(env) contract and what rake middleware shows
Rack is the interface spec between Ruby web servers and frameworks. Middleware intercepts and processes requests/responses, stacked like onion layers.
Routing & Controllers
What Are RESTful Routes in Rails? What One resources Line Creates
One line of resources generates 7 routes automatically
URLs designed per resource following REST principles. resources :posts generates 7 routes: index, show, new, create, edit, update, destroy.
Rails params and Strong Parameters: Reading Requests Safely
How URL, query, form and JSON values land in one hash, and blocking mass assignment
Access URL params, form data, JSON body via params hash. Strong Parameters (require/permit) whitelist allowed fields to prevent Mass Assignment attacks.
What Is before_action? Running Shared Code Around Rails Actions
The before, after and around variants, plus auth-check and record-loading patterns
Declaratively insert common logic (auth checks, data loading) before/after Controller actions with before_action, after_action, around_action.
How to Use Controller Concerns to Share Code Across Controllers
Reusing auth, pagination and search with include
Create modules in app/controllers/concerns/ and include them in multiple Controllers for code reuse. Used for auth, pagination, search, etc.
Many services in one Rails app — why your catch-all eats the next service
A lambda in a route constraints option drops the outer host constraint
Put a lambda constraint on a catch-all inside a per-host constraints block and that route stops checking the host. Rails replaces the outer block conditions with the route-level lambda. Check the host inside the lambda, or wrap the lambda in a block.
Models & Database
What Is ActiveRecord? Working with the Database Without Writing SQL
Basic CRUD and the query interface
Object-Relational Mapping. Auto-maps Ruby objects to DB tables, enabling CRUD via Ruby methods without writing SQL.
What Are Rails Migrations? Versioning Your Schema in Code
The basics of db:migrate and rollback
Define DB table creation/modification/deletion in Ruby code, executed chronologically for schema version control. Track and rollback DB changes like Git.
Rails Associations: How has_many and belongs_to Work
From 1:1 and 1:N to N:M with has_many :through
Declaratively define model relationships with belongs_to, has_many, has_one, has_many :through. Auto-connected when following foreign key conventions.
What Are Rails Validations? Checking Data Before It's Saved
presence, uniqueness, format and custom validations
Declare validations on models with the validates macro. Various checks (presence, uniqueness, length, format) run before DB save.
What Are Model Callbacks in Rails? Hooking into Save and Destroy
The execution order on create, and where after_commit fits
Hook into model lifecycle events (before_save, after_create, before_destroy) to auto-execute logic at specific points.
How to Use Rails Scopes to Name and Chain Common Queries
Including scopes with arguments and chaining examples
Name frequently used query conditions with scope macro for reuse. Chainable for readable complex queries.
What Is the N+1 Query Problem? Fixing It with includes
Plus how includes, preload and eager_load differ
Individually querying associated data in loops causes 1 (list) + N (each association) queries. Reduce to 2 queries with includes/preload/eager_load.
How to Use store_accessor to Treat jsonb Like Normal Attributes
Packing several values into one PostgreSQL jsonb column
jsonb is a PostgreSQL column type that stores JSON as binary. With store_accessor, you pack multiple values into one jsonb column and read/write them like regular columns.
find_or_initialize_by vs create_or_find_by: Surviving Concurrent Requests
Why RecordNotUnique happens — the order of find and create
The two methods run find and create in opposite order. find_or_initialize_by SELECTs first, create_or_find_by INSERTs first. If concurrent requests throw RecordNotUnique, switch to the latter.
Views & Frontend
How to Use ERB and Partials to Split Views into Reusable Pieces
Writing <%= %> and pulling markup out into partials
ERB (Embedded Ruby) is a template engine for embedding Ruby in HTML. Partials are reusable view fragments that reduce repetition.
Rails Layouts and yield: One Shared Frame for Every Page
Putting head, nav and footer in application.html.erb
Define common HTML structure (head, nav, footer) in application.html.erb layout and insert each page's unique content with yield.
How to Use form_with: Rails Forms That Handle CSRF and URLs
Pass a model and the create/update URL is picked for you
form_with helper auto-handles CSRF tokens, HTTP methods, and parameter naming. Passing a model object auto-determines create/update URL.
What Is Hotwire? How Turbo Updates Pages by Sending HTML
When to use Drive, Frames or Streams, and when React is the better call
Hotwire has the server send HTML instead of JSON, and Turbo slots it into the page. You will be able to pick between Drive, Frames and Streams, and fix the Content missing and form response errors yourself.
What Is Stimulus? Wiring JavaScript Through HTML Attributes
Using data-controller, data-action and data-target
Connect JavaScript behavior by adding data-controller, data-action, data-target attributes to HTML. HTML leads, JS is the "seasoning".
Why Stimulus lazyLoad Still Downloads Every Controller
importmap's pin_all_from defaults to preload: true. Change preload: false along with the eager-to-lazy line, then check names, call order and the first click
A login page was pulling 131 Stimulus controllers and filling Puma's slots. Swapping eagerLoadControllersFrom for lazyLoadControllersFrom alone doesn't fix it, because pin_all_from defaults to preload: true and prints every controller as a modulepreload link. Add preload: false, then check hyphenated file names, register order, silent import failures and the first click.
Authentication & Security
What Is Devise? The Gem That Adds Login and Sign-Up to Rails
From current_user and authenticate_user! to password resets
Authentication gem providing sign-up, login, logout, password reset, email verification, OAuth. Auto-generates helpers like current_user, authenticate_user!.
Why a password_digest Column Breaks Devise's inspect
Devise's password_digest(password) shadows a leftover has_secure_password column. Staging looked fine only because pry swallowed the exception
If a Devise model's table has a password_digest column, Devise's password_digest(password) method shadows the column reader, and inspect, as_json and to_json die with ArgumentError. Staging looked fine because pry swallows inspect errors. ignored_columns alone is not enough: select('users.*') brings the column back and the API token starts showing in plain text, so drop both with except in serializable_hash.
What Is CSRF? How Rails Blocks Forged Requests with Tokens
Why you get a 422, the null_session trap, and how it differs from SameSite
CSRF is when another site makes a logged-in user's browser send a request to your app. You will be able to trace a 422 and tell where turning the token check off is safe and where it isn't.
What Are Strong Parameters? Accepting Only the Fields You Allow
Preventing Mass Assignment attacks
Explicitly declare allowed fields with params.require(:model).permit(:field1, :field2) in Controller. Non-permitted fields are auto-ignored.
Tenant Isolation Query Patterns — Start from Organization Scope, Not Model.where
Query patterns that structurally prevent data leaks in multi-tenant Rails apps
In multi-tenant apps, global queries like Contract::Asset.joins(:contract).where(contracts: { organization_id: ... }) leak data if a single ID is wrong. Starting from organization.contracts makes query structure itself guarantee tenant isolation.
Why API keys are shown only once, and why we skipped the "show again" button
Store a SHA256 digest and a 12-char label. Even the system cannot recover the key
API keys are shown only once: the DB stores just a SHA256 digest and a 12-char label, so even the system cannot recover them. Lost it? Revoke and reissue.
Owner mode without login: secret-URL auth is one key to N browsers, not 1:1
Put a digest in the cookie and "log everyone out" comes free. Plus the day the key showed up in the log
For an app only I use, I skipped login: one visit to a secret URL sets a signed cookie. One key maps to N browsers and the server remembers nothing. Rotating the key logs everyone out. Logging out just one phone is impossible.
Testing
What Is RSpec? Writing Rails Tests That Read Like Sentences
The basics of describe, context, it and expect
Write tests like natural language with describe/context/it blocks. Verify with expect(actual).to eq(expected) syntax. Tests all layers of Rails.
How to Use FactoryBot to Build Test Data on the Fly
Using create(:user) and build(:post) instead of fixtures
Dynamically generate test data with Factory pattern instead of Fixtures. Create data on-the-fly with concise syntax like create(:user), build(:post).
What Are Request Specs? Testing Rails Through Real HTTP Requests
Checking status codes, redirects and rendered content
Simulate real HTTP requests with get, post, patch, delete methods and verify response status codes, redirects, and rendered content.
Advanced
Rails Background Jobs: Moving Slow Work Out of the Request
Active Job + Sidekiq for emails and external API calls
Process time-consuming tasks like email delivery, file processing, and external API calls asynchronously in background queues. Users get immediate responses.
Sidekiq: Deploys and the Async Job Pitfall
SIGTERM/SIGKILL — why long Sidekiq jobs die on every deploy
Async jobs can vanish entirely or get stuck forever in "running" state depending on deploy timing. Understanding the difference between SIGTERM (graceful) and SIGKILL (forced), how Sidekiq handles graceful shutdown, and the limits of OSS reveals why these incidents happen.
What Is Action Cable? Real-Time Features with Rails' WebSocket
Using it for chat, notifications and live updates
WebSocket framework built into Rails that pushes real-time data from server to client. Used for chat, notifications, and live updates.
Rails Caching: Which Kind to Use When
Fragment, Russian Doll, Low-Level, and when the cache refuses to clear
How to choose which layer to cache a slow screen at, and which store to use. With numbers from a 200-comment page, you will be able to explain why a cache sometimes refuses to clear.
Rails Asset Pipeline vs Vite: Sprockets, Webpacker and Vite Compared
Frontend asset management for JavaScript, CSS, images
Bundle JavaScript/CSS/images with Sprockets (legacy), Webpacker (deprecated), Vite (modern) and optimize cache with fingerprinting.
What Is Kamal? Deploying Rails to Any VPS with Docker
On small servers, build locally and push to a registry
Rails official deployment tool by DHH. Deploy to any VPS with Docker containers. For small servers like DigitalOcean, local build + push to registry is recommended.
Faraday open_timeout: Leave It Unset and It Takes Your timeout
I trusted Net::HTTP's 60-second default and my reasoning broke with it. A black-hole IP shows 3 s vs 1 s, then how to set each phase
Set only conn.options.timeout = 300 in Faraday and open_timeout is 300 seconds too, because adapter.rb does options[key] || options[:timeout]. My "zero OpenTimeouts, so 10 seconds is safe" argument assumed Net::HTTP's 60-second default, and it fell apart.
My Convention
Why We Avoid Helpers
My Convention — data logic in Controller, minimal Helpers
Rails Helpers are convenient but overuse causes global pollution, testing difficulties, and ambiguous responsibilities. Data processing in Controller, display-only in Helper.
DHH's Rails Coding Style
Vanilla Rails is enough — The 37signals philosophy
Coding principles practiced by Rails creator DHH. Minimize external libraries, map everything to CRUD, manage state as records instead of booleans.
Rails Open Source Code Reading
What Campfire's Code Teaches About DHH-Style Rails
37signals' chat app: has_secure_password and the Solid gems
Real-time chat app released by 37signals under the ONCE brand. has_secure_password instead of Devise, Solid series instead of Redis, CRUD-only without custom actions — the DHH style textbook.
Reading Writebook's Code: delegated_type and Edit History
37signals' publishing tool, plus its Access and Publication patterns
37signals' ONCE brand publishing app. Manages polymorphic content (Page/Section/Picture) with delegated_type, tracks edit history with Edit records. Same auth pattern as Campfire, but with unique patterns like Access control and Publication.
What Is Solid Queue? Rails 8 Background Jobs Without Redis
How FOR UPDATE SKIP LOCKED keeps workers from colliding
Rails 8 default ActiveJob backend. Processes background jobs using only database (PostgreSQL/MySQL/SQLite) instead of Redis/Sidekiq. Non-blocking polling with FOR UPDATE SKIP LOCKED.
What Is Solid Cache? Rails 8 Caching on the Database, Not Redis
Why SSDs allow a bigger cache, plus expiry and sharding
Rails 8 default cache store. Uses database (SSD) instead of Redis/Memcached for much larger caches. Write-based probabilistic expiration and Maglev consistent hashing for sharding.
Infra
Rails 8 + SQLite — Why It Works in Production
The era of no PostgreSQL has arrived — SQLite in production proven by 37signals
Rails 8 officially supports SQLite as a production database. Solid Queue (background jobs), Solid Cache (cache), Solid Cable (WebSocket) all run on SQLite. Proven in production by 37signals (Basecamp).
SQLite WAL Mode Explained — How It Works, Pros and Cons
How Write-Ahead Logging solves SQLite concurrency problems
How SQLite WAL mode works: writes go to a -wal file so reads never block. Enable it with PRAGMA journal_mode=WAL, plus the -shm file, checkpoints and backups.
Rails App Deployment SaaS Comparison
Practical comparison of Fly.io, Render, DigitalOcean, Fargate, Railway, Heroku
A practical guide to choosing the right PaaS/SaaS for deploying early-stage Rails projects. Compared by free tier, Docker support, PostgreSQL/SQLite compatibility, pricing structure, and scaling options.
A GitHub repo instead of a database: the real condition is an append-only event log, not "single user"
Why a bookmark app with zero migrations (app421) works across devices
Our YouTube bookmark app, app421, has no tables at all. Data lives as JSONL in the user's GitHub repo, a browser extension writes and Rails only reads. It works not because one person uses it but because of three things: append-only, line-oriented text, and a size you can read whole.
Puma Slot Exhaustion: Why CPU Sat at 21% During 60,000 502s
Tasks x workers x threads = 20 at once. Split ELB 5xx from target 5xx to find it, and scale on response time to catch it
CPU at 21%, memory at 37%, and the ALB returned 62,684 502/504s in 50 minutes. The app itself returned zero 5xx. Twenty Puma slots (2 tasks x 2 workers x 5 threads) ran dry at 296 req/s, and the health check queued in the same line and failed. CPU-based autoscaling never catches this.
Why remove_column Breaks INSERTs During a Rolling Deploy
Running db:migrate at boot only protects the new container. Meanwhile old code takes the traffic, and with partial_inserts = false it still writes the dropped column
Even if your container runs db:migrate before Puma starts, a rolling deploy leaves old containers serving traffic on the new schema for 1 to 3 minutes. Reproduced on Rails 8.0.4, SELECT and UPDATE pass and only INSERT fails, because load_defaults 7.0 sets partial_inserts to false. The fix is two releases: ignored_columns first, remove_column second.
Two Correct Commits, One Silent Regression: Why a Rails Auto-Link Feature Died Three Months Later
The scope for attaching and the scope for finding drifted apart, and no single diff showed it. A working ActiveRecord reproduction and the round-trip spec that catches it
One commit moved a filter into a display scope. A later one removed a string fallback. Each was right. Together they zeroed auto-linking only for orgs with no confirmed partners, and overall metrics stayed flat. By the end you can find the same drift in your app and pin it with a round-trip spec.