Model Change with Schemaless Changesets
Learn how to model changes to data without using a database.
We'll cover the following
We’ve used changesets to model changes to data that is persisted in our database, but we can easily imagine scenarios in which we want to present the user with the ability to input data that isn’t persisted. Consider the following examples:
- A guest checkout experience in which a user inputs their billing and shipping info without saving it.
- A gaming UI in which a user provides a temporary username for the lifespan of the game.
- A search form in which input is validated but not saved.
All of these scenarios require presenting some interface to the user for collecting input, validating that input, and managing the results of that validation. This is exactly what changesets and forms did for us in our ProductLive
views. Luckily for us, we can continue to use changesets in this way, even without schema-backed modules and data persistence.
In this lesson, we’ll see how to use schemaless changesets to model data that we won’t save inthe database. We’ll build a new LiveView that uses schemaless changesets to allow users to send promo codes for game purchases to their friends. Then, we’ll take a look at some of the tools that LiveView provides for working with forms.
Let’s dive in.
How to build schemaless changesets from structs
Simply put, we can use changesets with basic Elixir structs or maps—you don’t need to use Ecto
schemas to generate those structs. But, when we do use changesets with plain structs, our code needs to provide the type of information Ecto would normally handle.
That might sound confusing at first, but after a quick example, we’ll get the hang of it. All you need to do is call Ecto.Changeset.cast/4
. For the first argument, we’ll pass a tuple containing our struct and a map of our struct’s attribute types, and we’re off to the races.
Let’s take a look at a brief example. Then, we’ll outline a use-case for schemaless changesets in our Pento app and build it out together.
Open up IEx in the terminal below and key in this simple module definition for a game player:
Get hands-on with 1400+ tech skills courses.