Use Changesets Without Schemas

Learn how to use changeset without schemas.

We'll cover the following

Up to this point, our changesets have been based on the schemas defined in our music_db application, such as Artist, Genre, and so forth. Changesets don’t actually need Ecto schemas, though. They can be created with plain maps that define field names and types. This means that we can leverage changesets casting, filtering, and validation features, even if the data is not persisted in a database.

Let’s say that our application will have an “Advanced Search” feature. We’ll allow users to specify the number of different fields to help them find what they’re looking for, artist names, album titles, dates, and the like. We can validate the form using the features of Ecto.Changeset and then report any errors back to the user. Recall that changesets are just data structures and have a lot of utility before they are sent to the database.

The first step is to set up a map that defines the shape of the data we want to process. The keys should be the field names and the values should be the data types for each field. We can use any data types supported by the Ecto.Schema module. Here’s what we might use for our “Advanced Search” feature:

Get hands-on with 1200+ tech skills courses.