There is a user table with the name and game fields with the player1, player2 fields. How to relate this?
i did so:
-----model users-------------
schema "users" do
field :name, :string
has_many :games, Game
end
------model games---------
chema "games" do
belongs_to :user1, User, foreign_key: :player1
belongs_to :user2, User, foreign_key: :player2
end
def changeset(game, attrs) do
game
|> put_assoc(:user1, attrs["player1"], required: true)
|> put_assoc(:user2, attrs["player2"], required: true)
end
---------migration users------------
def change do
create table(:users) do
add :name, :string
end
end
------migration games---------------
def change do
create table(:games) do
add :player1, references(:users, on_delete: :delete_all)
add :player2, references(:users, on_delete: :delete_all)
end
end
:foreign_key - Sets the foreign key, this should map to a field on the other schema, defaults to the underscored name of the current schema suffixed by _id