Skip to content
Tutorials Center
My learning

Topics

Lesson 118 of 134 ยท Web and Ecosystem

ActiveRecord and Sequel Basics

Compare the two main Ruby ORMs. See how Sequel datasets and ActiveRecord models, migrations, validations, callbacks and associations work, using runnable plain-Ruby stand-ins.

An ORM (object-relational mapper) is the layer that lets you work with database tables as Ruby objects. Two libraries dominate the Ruby world. ActiveRecord is the ORM of Rails: every model class is tied to a table and every instance is a row that can save itself. Sequel is a separate gem with a different personality: it centres on datasets, immutable query objects you chain together, and treats models as an optional extra.

The lesson Database Access Ideas built a data mapper and a tiny ActiveRecord by hand. Here we go one level up. You will learn what a real project looks like, how the two libraries differ, and which features matter on day one: migrations, queries, validations, callbacks and associations. Neither gem is installed on our runner, so the real code is read-only, and each idea has a runnable stand-in written in plain Ruby. Once the stand-ins make sense, the real libraries will feel familiar.

Two styles of ORM

The difference shows in the first line of code you write.

Ruby
# ActiveRecord (read-only): a class per table, objects know how to save themselves
class Book < ApplicationRecord
  belongs_to :author
  validates :title, presence: true
end

Book.where(year: ..1970).order(:title).limit(5)
Ruby
# Sequel (read-only): a dataset is the central object, models are optional
DB = Sequel.sqlite
books = DB[:books]

books.where(year: ..1970).order(:title).limit(5)

Both read almost the same. The difference is in the philosophy:

ActiveRecord Sequel
Main object Model class (Book) Dataset (DB[:books])
Result of a query Model instances Plain hashes (or model instances if you use Sequel::Model)
Query builder where, order, relations Datasets, with a very expressive SQL DSL
Best known for Convention over configuration, Rails integration Flexibility, speed, close mapping to SQL
Shipped with Rails Yes No, but works with any framework

Neither one is "better". ActiveRecord wins when you build a Rails app, because everything else in Rails assumes it. Sequel shines in scripts, Sinatra or Roda apps, and anywhere you want to stay close to the SQL.

Sequel: datasets are immutable

The most important Sequel idea is that a dataset never changes. Every method such as where, order or limit returns a new dataset and leaves the old one alone. Nothing touches the database until you ask for results (all, first, each) or print the SQL with sql.

Because that is easy to copy, we can build a small dataset class that generates SQL text. It is the same trick the real library uses, minus the hundreds of features. Watch how the original books dataset stays unchanged after we chain from it.

Ruby An immutable, chainable dataset

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.

Look at the last line: books is still SELECT * FROM books after we derived old and top from it. That is why Sequel code is safe to share. You can keep a base dataset in a constant, such as ACTIVE_USERS = DB[:users].where(active: true), and every call site that chains from it gets its own copy.

Two details are worth noticing. First, the value "O'Brien" is escaped by doubling the quote. That is for demonstration only. The real libraries send values through the driver's bind or quoting machinery. You should never write your own escaping. Second, we used a Ruby Range for BETWEEN and an Array for IN. Real Sequel and ActiveRecord accept the same shapes, which is why where(year: 1900..1970) reads so naturally.

Here is the real Sequel API for the most common jobs (read-only):

Ruby
require "sequel"

DB = Sequel.sqlite   # in-memory database

DB.create_table :authors do
  primary_key :id
  String :name, null: false
end

DB.create_table :books do
  primary_key :id
  foreign_key :author_id, :authors
  String  :title, null: false
  Integer :year
end

authors = DB[:authors]
books   = DB[:books]

author_id = authors.insert(name: "Ursula")
books.insert(title: "Dune", year: 1965, author_id: author_id)

books.where { year < 1990 }.order(:title).all   # => [{id: 1, title: "Dune", ...}]
books.where(year: 1965).update(year: 1966)
books.where(title: "Dune").delete

Results come back as an array of plain hashes with symbol keys. Notice that where { year < 1990 } takes a block: inside it, year and < are rewritten into SQL, not evaluated by Ruby.

ActiveRecord: migrations first

In ActiveRecord the table structure lives in migrations, small Ruby files that describe a change to the schema. Rails runs them in order and records which have been applied, so every developer and every server ends up with the same database.

Ruby
# db/migrate/20260101120000_create_books.rb (read-only)
class CreateBooks < ActiveRecord::Migration[8.1]
  def change
    create_table :books do |t|
      t.string  :title, null: false
      t.integer :year
      t.references :author, foreign_key: true
      t.timestamps
    end

    add_index :books, :title
  end
end

The change method is reversible: Rails can roll the migration back by inverting each step. By convention the table name is the plural of the model (Book maps to books), and t.timestamps adds created_at and updated_at, which ActiveRecord fills in automatically. The Rails migration command that applies pending files is bin/rails db:migrate.

You never edit an old migration after it has been shared. If you made a mistake, write a new migration that fixes it.

The life of an ActiveRecord object

An ActiveRecord model goes through a well-defined lifecycle each time you save it. Understanding the order explains most surprises with validations and callbacks.

flowchart TD
  A["book.save"] --> B{"valid?"}
  B -- no --> C["return false<br/>errors filled in"]
  B -- yes --> D["before_save callbacks"]
  D --> E{"new record?"}
  E -- yes --> F["INSERT"]
  E -- no --> G["UPDATE changed columns"]
  F --> H["after_save callbacks"]
  G --> H
  H --> I["return true"]

Saving a record: validations run first, and nothing is written if they fail.

save returns false when validation fails and puts the messages in errors. save! raises ActiveRecord::RecordInvalid instead. The second form is useful in scripts and tests where you want a loud failure.

A model stand-in: validations, callbacks and dirty tracking

The next example is a small model base class. It has class-level macros (attribute, validates_presence_of, before_save), dirty tracking, and the same save flow as the diagram. The storage is an array, so everything is deterministic. If the metaprogramming looks new, define_method and hooks explain the techniques used.

Ruby A tiny ActiveRecord-style model

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 output shows the same behaviours you get from the real library. A new object is not saved, changes lists what you modified, the before_save callback strips the spaces from the title, and a failed validation fills errors without raising. Book.create is the "build and save!" shortcut.

Real ActiveRecord does much more: it generates the attribute methods from the table columns (you do not declare them), it keeps changes as { "year" => [1965, 1966] } with string keys, and it wraps every save in a database transaction. The shape is the same, though.

Associations

Tables are connected by foreign keys, and both libraries let you describe those connections once and then navigate them with plain method calls.

Ruby
# ActiveRecord (read-only)
class Author < ApplicationRecord
  has_many :books, dependent: :destroy
end

class Book < ApplicationRecord
  belongs_to :author
end

author = Author.find_by!(name: "Ursula")
author.books.where("year < ?", 1980).to_a
Book.includes(:author).each { |book| puts book.author.name }

has_many and belongs_to generate the methods author.books and book.author. The includes(:author) call is the cure for the N+1 problem from the previous lesson: it loads all needed authors with one extra query.

Ruby
# Sequel::Model (read-only)
class Author < Sequel::Model
  one_to_many :books
end

class Book < Sequel::Model
  many_to_one :author
end

Author.eager(:books).all   # two queries instead of N + 1

Sequel names the same relationships one_to_many and many_to_one, and uses eager for preloading. Here is a runnable stand-in for the has-many side: the association method does a lookup by foreign key and returns a fresh list each time.

Ruby has_many and belongs_to by hand

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 first part does one scan of BOOKS per author, which is the N+1 pattern in miniature. The group_by version scans once and then uses hash lookups. That is exactly the trade includes and eager make for you.

Choosing and getting started

A simple rule works for most projects:

  • Building a Rails app: use ActiveRecord. The framework, the generators and almost every gem expect it.
  • Writing a script, a small web service or a library: consider Sequel. It has no framework baggage and its dataset API is a good fit for reporting queries.
  • Whichever you choose, keep the database as the final judge. Add NOT NULL, unique and foreign-key constraints in migrations as well as Ruby validations. A validation protects your own code path; a constraint protects the data from every path, including a second app or a manual fix. The SQL tutorial explains constraints and transactions in depth.

Whatever the library, never put user input into a SQL string yourself. Pass hashes (where(name: name)) or placeholders (where("name = ?", name)). The security lesson Secure Ruby Code goes through this and other pitfalls.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a Sequel dataset method such as where return?

    Datasets are immutable. Each chained method returns a new dataset, and the database is only queried when you ask for results.
  2. 2. In ActiveRecord, what happens when book.save is called on a record that fails validation?

    save returns false and populates errors. Only save! (and create!) raise RecordInvalid.
  3. 3. Why do migrations exist?

    A migration is a versioned change to the schema. Rails records which ones have run, so every developer and server can reach the same structure.
  4. 4. Which pair best describes the has-many relationship in ActiveRecord?

    The table that holds the foreign key (books.author_id) gets belongs_to. The other side gets has_many.
  5. 5. Why should you still add database constraints when the model already has validations?

    Validations only run when records are saved through your model. Constraints are enforced by the database for every writer, including other apps and manual fixes.

Summary

  • ActiveRecord maps a table to a model class whose instances save themselves; Sequel centres on immutable, chainable datasets and plain hashes.
  • Neither query is sent until you read the results, so you can build queries in steps.
  • Migrations are ordered, versioned schema changes; never edit one that has been shared.
  • Saving follows a fixed lifecycle: validate, run before_save, INSERT or UPDATE, run after_save. save returns false on failure and save! raises.
  • Associations (has_many, belongs_to, or one_to_many, many_to_one) turn foreign keys into method calls; eager loading avoids N+1 queries.
  • Use validations and database constraints together, and always pass user input through hashes or placeholders.

Next: Rails MVC, Routing and Controllers