# Ecto vs ActiveRecord: Two Ways to Think About Your Database (and Where ROM Fits)

Author: Ziyan Junaideen
Published: 2026-11-22T06:10:05Z
Updated: 2026-11-22T06:10:05Z
Original: https://www.jdeen.com/blog/ecto-vs-activerecord-two-ways-to-think-about-your-database-and-where-rom-fits

![A red ruby tangled in cables wired straight into a database and to email, settings and notification icons, beside a tidy violet neon pipeline where data cards pass through a funnel with a check mark and a single gateway before reaching a database](https://sgp1.digitaloceanspaces.com/jdeen/uploads/958a6abb-f9ad-4046-b857-0826c973856e/ecto-vs-activerecord-header.webp)

I spent ten years with Ruby on Rails before most of my work moved to Elixir and Phoenix. Now that my next contract is likely to be a Ruby one, I've been looking at Rails again with fresh eyes, and the part that feels most different after a few years away is the database layer.

ActiveRecord and Ecto solve the same problem: get rows out of a database, validate changes, and put them back. They come from opposite ideas about where that work should live, and nearly every practical difference between them follows from that one choice.

One clarification first. Ecto isn't part of Phoenix, and ActiveRecord isn't tied to Rails. Phoenix generates Ecto code by default, but Ecto is a separate library, and ActiveRecord can run outside Rails. So this isn't really a framework comparison. It's a comparison of two ways to think about persistence.

### Two patterns

ActiveRecord follows Martin Fowler's *Active Record* pattern. An object wraps a database row and knows how to load and save itself:

```ruby
user = User.find(1)
user.name = "Ziyan"
user.save           # the object saves itself
user.posts.first    # and queries the database itself
```

Ecto is closer to Fowler's *Data Mapper* and *Repository* patterns. Your data is a plain, immutable struct, and one module, the `Repo`, does all of the database work:

```elixir
user = Repo.get!(User, 1)

user
|> User.changeset(%{name: "Ziyan"})
|> Repo.update()    # the struct knows nothing about the database
```

In ActiveRecord, persistence lives inside your domain objects. In Ecto, data is just values, and the database is something you call explicitly.

### How each one is built

**ActiveRecord puts everything in one class.** A model that inherits from `ActiveRecord::Base` gets its columns (read from the database when the app boots), associations, validations, callbacks, dirty tracking, a query interface built on Arel, persistence and serialization. The model is the centre of the application, and everything is reachable through it.

**Ecto splits the work into small modules**, each with one job:

<table>
<thead><tr><th>Module</th><th>Job</th></tr></thead><tbody><tr><td><code>Ecto.Schema</code></td><td>Maps a struct to a table, declared in code</td></tr><tr><td><code>Ecto.Changeset</code></td><td>Casts, validates and tracks a proposed change</td></tr><tr><td><code>Ecto.Query</code></td><td>Builds queries as data, checked at compile time</td></tr><tr><td><code>Ecto.Repo</code></td><td>The only place that talks to the database</td></tr><tr><td><code>Ecto.Multi</code></td><td>Describes a transaction as data before running it</td></tr><tr><td><code>Ecto.Migration</code></td><td>Schema changes, much like Rails migrations</td></tr></tbody>
</table>

Phoenix adds **contexts** on top, modules like `Accounts` or `Billing` that form the public interface of each part of the app. Business logic goes there, not in the schema. In Rails the same logic usually lives in the model, and moves into concerns or service objects once the model gets too big.

### Where the differences show up

#### Schemas: read from the database vs declared in code

ActiveRecord reads the table's columns at runtime, so attributes appear with no code at all. Ecto makes you list every field:

```elixir
schema "users" do
  field :email, :string
  field :name, :string
  field :password, :string, virtual: true
  has_many :posts, Post
  timestamps()
end
```

It's more typing, but the struct becomes the source of truth, and it opens up options ActiveRecord doesn't have: several schemas over one table, `embedded_schema` for data that has no table at all, and schemaless changesets for things like a search form.

#### Validation: model state vs changesets

This is the best idea in Ecto.

ActiveRecord keeps validations and change tracking inside the model's mutable state. That works until one model needs different rules in different situations. Then you reach for `on: :create`, custom validation contexts, `with_options`, or a separate form object.

An Ecto changeset is a value that describes a proposed change: which fields were allowed in, what changed, and what's wrong with it. You write as many as you need:

```elixir
def registration_changeset(user, attrs) do
  user
  |> cast(attrs, [:email, :name, :password])
  |> validate_required([:email, :password])
  |> validate_length(:password, min: 12)
  |> unique_constraint(:email)
end

def profile_changeset(user, attrs) do
  user
  |> cast(attrs, [:name])
  |> validate_required([:name])
end
```

Each changeset decides which fields it accepts, which also takes care of the job strong parameters do in a Rails controller. And because a changeset doesn't need a database, the same tool validates API input and forms that never get saved.

#### Uniqueness and database constraints

In ActiveRecord, `validates :email, uniqueness: true` runs a `SELECT` before inserting. Two requests at the same moment can both pass that check, so you still need a unique index, and then you have to rescue `ActiveRecord::RecordNotUnique` yourself.

Ecto's `unique_constraint(:email)` doesn't query anything. The insert runs, and if the database rejects it, Ecto turns that constraint error into an ordinary changeset error your form can show. `foreign_key_constraint`, `check_constraint` and `exclusion_constraint` work the same way. Ecto treats the database as the final authority on data integrity, and that turns out to be both simpler and correct.

#### Queries

ActiveRecord queries chain methods on a lazy relation, and scopes make them reusable:

```ruby
User.where(active: true).order(:name).limit(10)
```

For everyday queries this is hard to beat. Once a query needs subqueries, conditional joins or database functions, you end up in Arel or SQL strings.

Ecto queries are macros, checked when the code compiles, and they're plain data you can pass between functions:

```elixir
def active(query \\ User), do: where(query, [u], u.active)
def by_name(query), do: order_by(query, [u], u.name)

User |> active() |> by_name() |> Repo.all()
```

Named bindings, `fragment/1`, subqueries and `dynamic/2` keep complicated queries readable. Building a query never touches the database. Nothing runs until you hand it to the `Repo`.

#### Associations and N+1 queries

ActiveRecord loads associations lazily. `post.comments` quietly runs a query the first time you call it. That's convenient, and it's also the classic cause of N+1 queries. The fixes are `includes`, `preload` and `eager_load`, and since Rails 6.1, `strict_loading`, which raises when something loads lazily.

Ecto never loads lazily. If you didn't preload an association, it holds an `%Ecto.Association.NotLoaded{}` value, and using it raises an error. You ask for associations explicitly:

```elixir
posts = Post |> Repo.all() |> Repo.preload(comments: :author)
```

It's more ceremony, but no database call can hide in a template or a loop.

#### Callbacks

ActiveRecord callbacks, `before_save`, `after_create`, `after_commit` and the rest, are powerful. In a large app they also become the hardest thing to follow. Most Rails developers have asked "why does saving this record send an email?" at least once.

Ecto removed model callbacks in Ecto 2.0 on purpose. Side effects go in the context function that performs the action, in an `Ecto.Multi`, or in `prepare_changes/2` when something must happen inside the same transaction. Saving a record does exactly what the code in front of you says and nothing more.

#### Transactions

Rails has `transaction do ... end` blocks, savepoints and `after_commit`. Ecto has `Repo.transact/2` (`Repo.transaction/2` in older versions) and `Ecto.Multi`, which describes a transaction as a list of named steps:

```elixir
Ecto.Multi.new()
|> Ecto.Multi.insert(:invoice, invoice_changeset)
|> Ecto.Multi.update(:customer, customer_changeset)
|> Ecto.Multi.run(:ledger, fn repo, %{invoice: invoice} ->
  Ledger.record(repo, invoice)
end)
|> Repo.transact()
```

You can inspect a Multi, test it without running it, and combine several into one. If a step fails, you get `{:error, :customer, changeset, changes_so_far}` back, so you know exactly which step failed and why.

#### Tests and concurrency

Rails wraps each test in a transaction, which is fast, but running tests in parallel generally means separate processes, each with its own database.

Ecto's SQL sandbox gives each test process its own transaction on one shared database, so tests marked `async: true` run side by side. In a large test suite that's a real difference in speed. It depends on the BEAM's lightweight processes as much as on Ecto's design, so it's not something a Ruby library can copy easily.

### Side by side

<table>
<thead><tr><th></th><th>ActiveRecord</th><th>Ecto</th></tr></thead><tbody><tr><td>Pattern</td><td>Active Record</td><td>Data Mapper / Repository</td></tr><tr><td>Records</td><td>Mutable objects that save themselves</td><td>Immutable structs, saved through <code>Repo</code></td></tr><tr><td>Schema</td><td>Read from the database at runtime</td><td>Declared in code</td></tr><tr><td>Validation</td><td>On the model, with contexts</td><td>Changesets, one per use case</td></tr><tr><td>Uniqueness</td><td><code>SELECT</code> before insert, plus an index</td><td>Database constraint, mapped to an error</td></tr><tr><td>Queries</td><td>Chained relation, Arel for complex cases</td><td>Compile-time macros, queries as data</td></tr><tr><td>Associations</td><td>Lazy by default, <code>strict_loading</code> optional</td><td>Never lazy, explicit <code>preload</code></td></tr><tr><td>Side effects</td><td>Callbacks</td><td>Context functions, <code>Ecto.Multi</code></td></tr><tr><td>Parallel tests</td><td>Separate processes and databases</td><td>Sandbox, one database</td></tr><tr><td>Ecosystem</td><td>Huge</td><td>Smaller, growing</td></tr></tbody>
</table>

### What each one does well

**ActiveRecord** is the fastest way I know to go from an idea to a working CRUD app. Conventions remove decisions, the schema comes for free, and `user.posts.published.recent` reads almost like English. Its ecosystem is enormous: auditing, search, soft deletes, encryption, single-table inheritance, polymorphic associations and `delegated_type` are all built in or one gem away.

The cost shows up later, as database calls hidden behind method calls, callback chains, fat models, and domain logic that can't be unit tested without a database.

**Ecto** is predictable. Every database call goes through the `Repo`, changesets are useful far beyond the database, constraints are first-class, queries compose cleanly, and the test suite runs in parallel. Its cost is more code: declaring fields, writing changesets, preloading by hand. You'll also build more yourself, because polymorphic associations and inheritance aren't built in, and Ecto nudges you toward other designs.

The way I'd put it: **ActiveRecord is designed to make the first year of a project fast, and Ecto is designed to keep years three to ten easy to understand.** Rails has been moving in Ecto's direction for a while, with `strict_loading`, form objects, the attributes API, and community advice against callbacks. It just keeps those changes inside the Active Record pattern rather than switching patterns.

### What about ROM?

When I mention this to Ruby developers, someone usually asks about ROM. Ruby does have a data mapper.

The original DataMapper gem, despite its name, was mostly Active Record underneath: you included `DataMapper::Resource` and called `save` on the object. Its planned rewrite, DataMapper 2, was meant to become a true data mapper and was eventually renamed **ROM (Ruby Object Mapper)**. ROM looks a lot like Ecto:

- **Relations** for reading data and **commands** or changesets for writing it, kept separate
- Plain, immutable structs as results
- No lazy loading. You combine relations explicitly.
- No model callbacks
- Validation handled by `dry-validation` contracts, outside the persistence layer

It's the default database layer in Hanami 2.2, which is the best place to see it in its natural setting. Inside Rails, though, you fight everything that expects ActiveRecord: form helpers, authentication gems, admin panels, Active Storage. ROM's community is small, and validation, persistence and constraint handling are spread across separate libraries rather than combined the way Ecto's changesets combine them.

My own experience with ROM was outside SQL entirely. I used it with XML and CSV files from remote sources. It handled the mapping well, but we had to drop it for the larger feeds, because memory use became a problem as the files grew. That's a narrow use case and not a verdict on ROM with a database, but it's worth knowing that its non-SQL adapters aren't where most of the work has gone.

ROM shows that Ruby can express the same ideas as Ecto. The difference is what each ecosystem treats as normal. In Rails, ActiveRecord is the default and everything around it assumes it. In Phoenix, Ecto is the default, so explicit persistence is just how things are done.

### My conclusion

I'm happy to go back to ActiveRecord. For a lot of applications its trade-offs are the right ones, and Rails has made it safer over the years. But Ecto changed how I think about data. Changesets, explicit preloading and constraints mapped to errors are habits I'll take back to Ruby, whether that means `strict_loading` everywhere, form objects instead of validation contexts, or keeping callbacks to a minimum.

If I'm starting something that I expect to grow for years, with many people working on it, I'll still choose Ecto. Being able to read a function and know exactly what it does to the database is worth the extra typing.
