DEV Community

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

Posted on

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.

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

Top comments (0)