Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Active Record Models

Active Record: Models and Databases

Learn what Active Record is in Rails: how a model class maps to a table, rows become objects, columns become attributes, and conventions connect them. Includes a runnable mini ORM stand-in.

Almost every web app stores data. In Rails, the model layer handles that, and the default tool is Active Record, an object-relational mapper (ORM). It follows the pattern of the same name: a class represents a table, an object represents one row, and the columns become the object's attributes. You work with Ruby objects and Active Record writes the SQL.

Active Record needs a real database (SQLite, PostgreSQL or MySQL) and the Rails gems, so the Rails code here is read-only. To understand the mechanism, you will also build a mini ORM in plain Ruby that runs on this site. It is a teaching stand-in, not the real thing.

A model is a class plus a table

You create a model with the generator, which also writes a migration (see migrations):

Terminal
# read-only
bin/rails generate model Article title:string body:text published:boolean

The model file is nearly empty:

Ruby
# app/models/article.rb  (read-only)
class Article < ApplicationRecord
end

That one line is enough. Because the class is named Article, Active Record looks for a table called articles (lowercase, plural), and builds attribute methods from the table's columns. This is convention over configuration from the conventions lesson at work.

Ruby side Database side
class Article table articles
object Article.new one row
attribute article.title column title
primary key article.id column id

You can inspect what Active Record learned:

Ruby
# read-only: rails console
Article.table_name        # => "articles"
Article.column_names      # => ["id", "title", "body", "published", "created_at", "updated_at"]
Article.columns_hash["title"].type   # => :string
Article.primary_key       # => "id"
flowchart LR
  C["Article.where(published: true)"] --> AR["Active Record"]
  AR -->|"SQL SELECT"| DB[("articles table")]
  DB -->|"rows"| AR
  AR --> O["Article objects"]

Active Record turns Ruby calls into SQL and rows back into objects.

Naming rules

Rails derives names with an inflector. You mostly do not think about it, but you must know the pattern:

  • Model: singular, CamelCase (BlogPost).
  • Table: plural, snake_case (blog_posts).
  • Foreign key: singular model name plus _id (blog_post_id).
  • Irregular words work: Person maps to people, Child to children.

If you must use an old table name, override it: self.table_name = "legacy_articles". Overriding is a smell for new apps, so use it only for databases you do not control.

Stand-in: a mini ORM in plain Ruby

The next stand-in rebuilds the core trick. A class inherits from MiniRecord, declares its columns, and gets a table name (Article becomes articles), a create method, all, find and where. Rows live in an array instead of a database.

Ruby Stand-in: a mini Active Record

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

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

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

The real Active Record does the same job with much more: it generates SQL, reads column types from the database, casts values, tracks changes and caches schema information. The shape is identical, though: a subclass, a table name derived from the class name, attribute methods from columns, and class-level finders.

Where models live and what they do

All models inherit from ApplicationRecord, which inherits from ActiveRecord::Base. Put code that applies to every model in ApplicationRecord. A model class is the right place for:

  • data rules (validations, covered in validations),
  • relationships to other models (associations),
  • queries with a name (scopes),
  • small domain methods like article.publish! or user.full_name.

Models are plain Ruby classes too, so a model does not need to be an Active Record. Plain objects (often called POROs) for non-database logic go in app/models as well.

Connecting to a database

The database is configured in config/database.yml, with one block per environment (see environments). A new app uses SQLite by default:

YAML
# config/database.yml  (read-only)
default: &default
  adapter: sqlite3
  max_connections: 5
  timeout: 5000

development:
  <<: *default
  database: storage/development.sqlite3

production:
  <<: *default
  database: storage/production.sqlite3

To start with PostgreSQL or MySQL, run rails new blog --database=postgresql. Active Record hides most differences between databases, which is why the same model code works across them. When you do need engine-specific features (JSON columns, full-text search), the adapter provides them.

Rails 8 apps ship with SQLite for the main database, plus separate SQLite files for the cache, job queue and cable. Production-grade setups on a single server are possible, but many teams still choose PostgreSQL.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A class BlogPost < ApplicationRecord maps to which table by convention?

    Table names are plural snake_case of the model name.
  2. 2. In Active Record, what does one object represent?

    Each Article object wraps one row of the articles table.
  3. 3. Which file configures the database connection for each environment?

    database.yml defines adapter, database name and pool settings per environment.
  4. 4. Why does class Article < ApplicationRecord; end already give you article.title?

    Active Record inspects the table schema and generates attribute readers and writers.

Summary

  • Active Record maps a class to a table, an object to a row and a column to an attribute.
  • Naming conventions (singular model, plural table, _id foreign keys) make configuration unnecessary.
  • A model starts as an empty subclass of ApplicationRecord and grows rules, relationships and queries.
  • config/database.yml picks the database per environment; the adapter hides most differences.
  • The mini ORM stand-in shows the mechanism but is no replacement for the real library.

Next: Migrations and the Schema