Schemas and Tables

Learn about the downsides to locking schemas to tables and the advantages of keeping them flexible.

Downsides to locking schemas to tables

When we set up schemas for the first time, it is natural to add fields that exactly match our database tables. However, this can have some unintended side effects down the line. As we’ve seen, schemas become the backbone of our changesets, and changesets are what we use to parse user-submitted data and convey error messages about that data to the user.

For example, the phoenix_ecto package implements behaviors for the Phoenix web framework such that changesets can be used as the backing data structure for Phoenix forms. To take advantage of the conveniences provided by the Phoenix.Form module, our web forms need to match our changeset structure (and therefore the underlying schema) as much as possible.

Therefore, we turn our database tables into the blueprint for our user interface without really intending to.

This is fine occasionally, but tables in relational databases don’t always make for user-friendly forms. A strict set of rules binds tables to maximize their efficiency, and that’s an entirely different concern than how to present a set of fields to an end-user in the friendliest manner possible.

Ecto gives us the flexibility to break out of this pattern. Schemas allow us to create data structures that work independently from the database without losing the conveniences that packages like phoenix_ecto provide.

With Ecto, we can distinguish between how we collect data and how we store data.

Get hands-on with 1200+ tech skills courses.