Getting Started on Elixir and Ecto Part 4
Kenzy Limon
Posted on November 2, 2022
Creating and Validating input Data
To insert a new record into our tasks
table, run this code:
task = %Taskers.Tasks{}
Taskers.Repo.insert(task)
To insert the data into our database, we call insert
. which is the module that uses Ecto to talk to our database. A successful insertion will return a tuple, like so:
{:ok, %Taskers.Tasks{__meta__: #Ecto.Schema.Metadata<:loaded, "tasks">, title: nil, id: 1, ...}}
The :ok
atom can be used for pattern matching purposes to ensure that the insertion succeeds.
{:ok, tasks} = Taskers.Repo.insert person
NOTE: In Ecto, you may wish to validate changes before they go to the database. For this, Ecto has changesets. Changeset will only allow defined parameters through and anything not in the list will be ignored.
This insertion will fail since the required values are not passed. The first return element is a tuple :error
which contains the specifics of the error
We can access these error messages by doing some pattern matching:
NOTE: Since changeset had errors, no record was inserted into the tasks table. For a better way to handle changeset, use a case statement on the turple.
To show these error messages in a more human-friendly way, we can use Ecto.Changeset.traverse_errors/2:
This will return the following output:
%{
user_id: ["can't be blank"],
title: ["can't be blank"],
}
Posted on November 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.