Ruby on Rails Reference
Free reference guide: Ruby on Rails Reference
About Ruby on Rails Reference
The Ruby on Rails Reference is a structured, searchable cheat sheet covering the key conventions and APIs of the Rails web framework. It spans six core categories — Routing, Model, Controller, View, Migration, and Test — giving Rails developers a single place to look up any syntax, generator command, or pattern. Each entry includes a real code example, making it practical for both new Rails developers learning the framework and experienced developers who need a quick reminder of method signatures or generator syntax.
Ruby on Rails follows the Model-View-Controller (MVC) pattern and heavily emphasizes convention over configuration. This reference covers the routing layer in depth: basic GET and POST routes, the `resources` helper that generates all seven RESTful routes at once, nested resources for hierarchical associations, namespace grouping for admin areas, and root path configuration. The Model section covers ActiveRecord associations (`has_many`, `belongs_to`, `has_many :through` for many-to-many relationships), validation macros (`validates :field, presence: true, length: { minimum: 5 }`), and named scopes for reusable query fragments.
The Controller section covers the `before_action` callback for DRY setup logic, Strong Parameters with `params.require(:model).permit()` for safe mass assignment, and the `render`/`redirect_to` response pattern. The View section covers ERB template syntax (`<%= %>` for output, `<% %>` for execution), partial rendering with `render partial:`, the `link_to` and `form_with` helpers. The Migration section covers `rails db:migrate`, `add_column`, `create_table`, and `add_index`. The Test section covers Rails' built-in test framework with `assert_equal`, `assert_difference`, `assert_response`, and YAML fixtures.
Key Features
- Covers 6 categories: Routing, Model, Controller, View, Migration, Test
- Routing: GET/POST routes, resources (RESTful), nested resources, namespace, root path
- ActiveRecord: has_many, belongs_to, has_many :through, validates, named scopes
- Controller: before_action callbacks, Strong Parameters (params.require.permit), render/redirect_to
- View: ERB tags (<%= %>, <% %>), render partial, link_to helper, form_with model builder
- Migration: rails db:migrate/rollback, add_column, create_table with t.references, add_index
- Test: rails test, assert_equal, assert_difference, assert_response :success, YAML fixtures
- 100% client-side — no sign-up, no download, no data sent to any server
Frequently Asked Questions
What does `resources :articles` generate in Rails routing?
`resources :articles` generates seven RESTful routes: GET /articles (index), GET /articles/new (new), POST /articles (create), GET /articles/:id (show), GET /articles/:id/edit (edit), PATCH/PUT /articles/:id (update), and DELETE /articles/:id (destroy). Each route maps to the corresponding controller action. You can use `only:` or `except:` to restrict which routes are generated, and nest resources with a block to create nested routes like `/articles/:article_id/comments`.
What is the difference between has_many :through and has_and_belongs_to_many?
`has_many :through` creates a many-to-many relationship via an explicit join model (e.g., Appointments joining Physicians and Patients). This is preferred when you need to store additional attributes on the join record or add validations to it. `has_and_belongs_to_many` creates a direct many-to-many relationship with a join table but no model, so you cannot add attributes to the join. Use `has_many :through` for most cases as it gives more flexibility.
What are Strong Parameters and why are they needed?
Strong Parameters prevent mass assignment vulnerabilities by requiring explicit whitelisting of permitted attributes. Without them, an attacker could submit additional fields in a form (like `admin: true`) and update sensitive model attributes. In your controller, use `params.require(:model_name).permit(:field1, :field2)` to create a safe parameters hash. Rails will raise an `ActionController::ForbiddenAttributesError` if you try to pass raw `params` directly to `create` or `update`.
How do database migrations work in Rails?
Migrations are Ruby classes that describe changes to your database schema in a database-agnostic way. Run `rails generate migration AddColumnToTable column:type` to create a migration file, then `rails db:migrate` to apply it. Rails tracks which migrations have been run in the `schema_migrations` table. Use `rails db:rollback` to undo the last migration. The `change` method handles both up and down directions for reversible operations; use separate `up` and `down` methods for non-reversible changes.
What is the before_action callback used for in Rails controllers?
`before_action` runs a method before one or more controller actions execute. It is commonly used to look up a resource (`@article = Article.find(params[:id])`), require authentication, or set up shared instance variables. Use `only: [:show, :edit, :update, :destroy]` to restrict which actions trigger the callback, or `except:` to exclude specific actions. Multiple `before_action` declarations run in order. You can halt the chain by rendering or redirecting inside the callback.
How do Rails named scopes work?
Named scopes are reusable query fragments defined on a model with `scope :name, -> { query }`. For example, `scope :published, -> { where(published: true) }` lets you call `Article.published` anywhere in your code. Scopes are chainable: `Article.published.recent` works if you also define `scope :recent, -> { order(created_at: :desc) }`. Scopes return an ActiveRecord::Relation, so they compose well with other scopes, `where` clauses, and `limit`.
How does the Rails test framework work?
Rails includes a built-in test framework based on Minitest. Test files live in `test/models/`, `test/controllers/`, etc. Run tests with `rails test` or target a specific file. Test methods start with `test "description" do ... end`. Common assertions include `assert_equal expected, actual`, `assert_difference "Model.count", 1 do ... end` (verifies a count changes), and `assert_response :success` (checks HTTP 200). Load test data with YAML fixtures defined in `test/fixtures/`.
What is the difference between render and redirect_to in Rails?
`render` renders a view template and returns a 200 response without making a new HTTP request. It is used when a form submission fails validation — you re-render the form with error messages while keeping the submitted data available. `redirect_to` returns a 302 (or 301) response that tells the browser to make a new GET request to a different URL. It is used after a successful create/update/destroy to prevent form resubmission on browser refresh (the Post/Redirect/Get pattern).