Hi guys! I am having trouble inserting data into the database. Here is my schema with changeset:
defmodule CompanyVisualisation.CompanyVisualisation do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :email, :string
field :name, :string
field :salary, :integer
field :surname, :string
end
@doc false
def changeset(company_visualisation, attrs) do
company_visualisation
|> cast(attrs, [:name, :surname, :email, :salary])
|> validate_required([:name, :surname, :email, :salary])
|> unique_constraint(:email, name: "users_user_email", message: "Email is already taken.")
end
end
and here is the code I am trying to run;
changeSet = CompanyVisualisation.CompanyVisualisation.changeset(%CompanyVisualisation.CompanyVisualisation{}, %{"name" => name, "surname" => surname, "email" => email, "salary" => salary})
if changeSet.valid? do
IO.inspect(changeSet)
case CompanyVisualisation.Repo.insert(%CompanyVisualisation.CompanyVisualisation{:name => name, :surname => surname, :email => email, :salary => String.to_integer(salary)}) do
{:ok, _struct} ->
Error is in the case statement, that constraint error when attempting to insert struct
and
users_email_index (unique_constraint)
If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call `unique_constraint/3` on your changeset with the constraint
`:name` as an option.
The changeset has not defined any constraint.
The thing I want to achieve is to validate an email and check, whether it is not already taken (that’s why it is unique). Where do I have mistakes?