Hi.
I want to create a CRUD where I could create a user and a token associated with the user and created the second one only if the user exists (foreign key constraint).
I started with migrations:
- priv/repo/migraions/20190530142317_create_users.exs
defmodule Backend.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :first_name, :string, null: false
add :second_name, :string, null: false
add :email, :string, null: false, unique: true
add :password, :string, null: false
add :is_active, :boolean, default: false, null: false
timestamps()
end
create unique_index(:users, [:email])
end
end
- priv/repo/migraions/20190607183748_create_tokens.exs
defmodule Backend.Repo.Migrations.CreateTokens do
use Ecto.Migration
def change do
create table(:tokens) do
add :token, :string
add :user_id, references(:users)
timestamps()
end
end
end
And follow up with schemas:
- lib/backend/auth/user.ex
defmodule Backend.Auth.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :first_name, :string, null: false
field :second_name, :string, null: false
field :email, :string, null: false, unique: true
field :password, :string, null: false
field :is_active, :boolean, default: true
has_one :tokens, Auth.Backend.Token
timestamps()
end
@doc false
def changeset(user, attrs) do
user
|> cast(attrs, [:first_name, :second_name, :email, :password, :is_active])
|> validate_required([:email, :password, :first_name, :second_name])
|> unique_constraint(:email, name: :users_email_index)
end
end
- lib/backend/auth/token.ex
defmodule Backend.Auth.Token do
use Ecto.Schema
import Ecto.Changeset
schema "tokens" do
field :token, :string
belongs_to :users, Backend.Auth.User
timestamps()
end
@doc false
def changeset(token, attrs) do
token
|> cast(attrs, [:token])
|> cast_assoc(:users)
|> assoc_constraint(:users)
|> validate_required([:token])
end
end
I access the token create endpoint with data as follows:
{
"token": {
"token": "token_test123",
"user_email": "wor@kth.se",
"user_id": 1
}
}
I get back status 201 Created, but looking up the record in the database the user_id field is empty.
What am I missing?
Regards,
Wojciech