Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

13 - Phoenix crash course #13: Ecto data persistence

Learn how to persist and query data using Ecto's Repo module in Phoenix applications

By Daniel Bergholz • Aug 19, 2025

Learn how to persist and query data using Ecto’s Repo module in Phoenix applications.

Repo module

The main gateway for database operations in Phoenix/Ecto. Use functions like Repo.all, Repo.insert, Repo.get, and Repo.get_by to work with data.

Querying and inserting data

  • Query all: Repo.all(Product) returns all products
  • Insert (no validation): Repo.insert(%Product{...}) (bypasses changeset)
  • Insert with validation: Preferred—build a changeset first (Product.changeset(%Product{}, params)) then insert: Repo.insert(changeset)

Persistence workflow

  • Use the .iex.exs file to save aliases/imports for easier command-line workflow
  • Always use changesets when writing to the DB (run validations, auto-generate fields, etc.)

More advanced queries

  • Use Ecto.Query for filtering, selecting, custom logic:
    from(p in Product, select: p.slug, where: p.console == "pc")
    Repo.all(query)

Controller refactor

  • Replace mock in-memory lists with Repo calls
  • Use Repo.all(Product) for index actions, Repo.get_by(Product, slug: slug) for show actions
  • Tip: Route product detail pages by slug instead of ID for readable URLs

HEEx update

  • Pass the whole product struct to function components, not just the name
  • Display product lists as links to detail pages using slugs and verified routes

Best Practice

Accessing DB directly in controllers works for demos, but proper Phoenix projects should use contexts (separation of business logic from web/UI code). This comes in the next video.

Summary

This episode explains how to actually persist (insert/query) data in Phoenix using Ecto’s Repo module, best practices for using changesets, basic querying/saving patterns, and connecting the UI to the DB for real dynamic pages.

Related

#phoenix-and-elixir #phoenix-crash-course #daniel-bergholz