DEV Community

Cover image for Getting Started on Elixir and Ecto Part 4
Kenzy Limon
Kenzy Limon

Posted on

3

Getting Started on Elixir and Ecto Part 4

Creating and Validating input Data

To insert a new record into our tasks table, run this code:

task = %Taskers.Tasks{}
Taskers.Repo.insert(task)
Enter fullscreen mode Exit fullscreen mode

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, ...}}
Enter fullscreen mode Exit fullscreen mode

The :ok atom can be used for pattern matching purposes to ensure that the insertion succeeds.

{:ok, tasks} = Taskers.Repo.insert person
Enter fullscreen mode Exit fullscreen mode

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.

def changeset(task, params \\ %{}) do
task
|> Ecto.Changeset.cast(params, [:title, :description, ...])
|> Ecto.Changeset.validate_required([:title, :description, ...])
end
task = %Taskers.Tasks{}
changeset = Taskers.Tasks.changeset(task, %{})
Taskers.Repo.insert(changeset)

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

{
:error, #Ecto.Changeset<action: :insert, changes: %{},
errors: [user_id: "can't be blank", title: "can't be blank", ...],
data: #Taskers.Tasks<>, valid?: false>
}

We can access these error messages by doing some pattern matching:

{:error, changeset} = Taskers.Repo.insert(changeset)
///Get the errors by doing :
changeset.errors
Return value : [user_id: "can't be blank", title: "can't be blank"]
///You can also check even before doing an insertion by
changeset.valid?
Return value : false

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.

case Taskers.Repo.insert(changeset) do
{:ok, task} ->
# do something with task
{:error, changeset} ->
# do something with changeset
end

To show these error messages in a more human-friendly way, we can use Ecto.Changeset.traverse_errors/2:

traverse_errors(changeset, fn {msg, opts} ->
Enum.reduce(opts, msg, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)

This will return the following output:
%{   
   user_id: ["can't be blank"],
   title: ["can't be blank"],
 }
Enter fullscreen mode Exit fullscreen mode

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay