Cast and Filter
Learn how to cast and filter data.
The following example inserts a new Artist
record based on data supplied by the user:
import Ecto.Changesetparams = %{name: "Gene Harris"}changeset =%Artist{} \|> cast(params, [:name]) \|> validate_required([:name])case Repo.insert(changeset) do{:ok, artist} -> IO.puts("Record for #{artist.name} was created."){:error, changeset} -> IO.inspect(changeset.errors)end
As this example demonstrates, changesets help us with the entire life cycle of making a change, starting with raw data and ending with the operation succeeding or failing at the database level. Let’s now zoom in on each step.
The first step is to take the raw input data that we want to apply to the database and generate an Ecto.Changeset
struct. We call this “casting and filtering” because we perform any needed type casting operations, like turning a string into an integer, and filter out any values we don’t want to use. We can do this two different ways, depending on where our data is coming from. We’ll look at both in the following sections.
Create changesets using internal data
If the data is internal to the application, we can create a changeset using the Ecto.Changeset.change
function. Here’s how we would create a changeset that inserts a new Artist
record:
import Ecto.Changesetchangeset = change(%Artist{name: "Charlie Parker"})
The import
statement makes all of the functions in Ecto.Changeset
available to our code. We won’t include this in the rest of the examples for brevity.
The process of making changes to an existing record is similar, but instead of passing in a new struct, ...