Ecto vs ActiveRecord: Managing Schema Changes in Elixir

Source code editor under colorful lighting
Photo by Jakub Żerdzicki on Unsplash. Visual editorial reference, not a verified screenshot of the software discussed. · View original image

When I move from Ruby on Rails to Elixir and Phoenix, Ecto is the first major change in how I think about persistence. Rather than putting every responsibility in a model instance, Ecto provides a set of composable tools: Ecto.Schema declares data structures, Ecto.Changeset validates and transforms changes, Ecto.Query builds composable queries, and Ecto.Repo interacts with the database. Each piece has a distinct job.

Comparison between ActiveRecord callbacks and explicit Ecto changesets and repository operations.
Original technical diagram comparing responsibilities and data flow, not execution speed.

The Mental Model Behind Callbacks

With ActiveRecord, it is common to define a callback such as before_save :do_something. It runs as part of a record’s lifecycle. That is convenient—until five callbacks depend on one another, their execution order becomes difficult to track, or a side effect causes a test to fail.

Ecto takes a different approach: changesets make validation and transformation explicit.

def changeset(user, attrs) do
  user
  |> cast(attrs, [:name, :email])
  |> validate_required([:name, :email])
  |> validate_format(:email, ~r/@/)
  |> unique_constraint(:email)
end

Each pipeline step transforms the changeset. When validation fails, the changeset carries the relevant errors. There is no hidden global state or callback chain to reconstruct.

Conceptual illustration of Ecto schema, changeset, and repository responsibilities compared with ActiveRecord.
Original editorial illustration summarizing the article's concepts; not a screenshot or measured test.

Change Your Mental Model, Not Just Your Code

One trap when migrating is to reproduce ActiveRecord-style callbacks through helper functions called from controllers. It is more useful to embrace explicit boundaries: changesets define validation and transformations, while operations such as Repo.insert/1 are responsible for database writes. That separation becomes especially valuable as an application grows.

Conclusion

Ecto asks for more explicit code. In return, a persistence workflow can be read from top to bottom without jumping through several callback definitions. After working this way for a while, returning to implicit model hooks can feel surprisingly opaque.