Note that you should only have one schema module for User and one for Team, so somehow these have been duplicated in your project (maybe by running the generators twice?). Your migrations are duplicated as well. It will be simpler to have the migration for Team run before the migration for User as one of the fields in User relies on the Team table existing (otherwise you will need a third migration that amends the User table after the Team table has been created). You can try to delete the duplicate files, or maybe it’s easier to start again?
If your user is setup like this:
defmodule Userteam1.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field(:name, :string)
field(:password, :string)
field(:role, :string)
belongs_to(:team, Userteam1.Team)
timestamps()
end
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :password, :role, :team_id])
|> validate_required([:name, :password, :role, :team_id])
end
end
then it will have a team
and team_id
field:
iex(1)> %Userteam1.User{}
%Userteam1.User{
__meta__: #Ecto.Schema.Metadata<:built, "users">,
id: nil,
inserted_at: nil,
name: nil,
password: nil,
role: nil,
team: #Ecto.Association.NotLoaded<association :team is not loaded>,
team_id: nil,
updated_at: nil
}
and if your team is setup like this:
defmodule Userteam1.Team do
use Ecto.Schema
import Ecto.Changeset
schema "teams" do
field(:name, :string)
has_many(:users, Userteam1.User)
timestamps()
end
def changeset(team, attrs) do
team
|> cast(attrs, [:name])
|> validate_required([:name])
end
end
then it will have a users
field:
iex(2)> %Userteam1.Team{}
%Userteam1.Team{
__meta__: #Ecto.Schema.Metadata<:built, "teams">,
id: nil,
inserted_at: nil,
name: nil,
updated_at: nil,
users: #Ecto.Association.NotLoaded<association :users is not loaded>
}
For this to work with the db, your migration for users should look like this (provided the migration for teams is before the migration for users, otherwise you will need to have two migrations for users with an alter table
instruction in the second one):
defmodule Userteam1.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add(:name, :string)
add(:password, :string)
add(:role, :string)
add(:team_id, references(:teams))
timestamps()
end
end
end
I forked your project on Github, made the changes above, and it worked okay.