Add a relationship between a user and links.

dev
KKlochko 8 months ago
parent 1b6651bab9
commit 499c5e5cc2

@ -2,12 +2,15 @@ defmodule LinkShortener.Accounts.User do
use Ecto.Schema use Ecto.Schema
import Ecto.Changeset import Ecto.Changeset
alias LinkShortener.Links.Link
schema "users" do schema "users" do
field :email, :string field :email, :string
field :password, :string, virtual: true, redact: true field :password, :string, virtual: true, redact: true
field :hashed_password, :string, redact: true field :hashed_password, :string, redact: true
field :current_password, :string, virtual: true, redact: true field :current_password, :string, virtual: true, redact: true
field :confirmed_at, :utc_datetime field :confirmed_at, :utc_datetime
has_many :links, Link
timestamps(type: :utc_datetime) timestamps(type: :utc_datetime)
end end

@ -3,10 +3,13 @@ defmodule LinkShortener.Links.Link do
import Ecto.Changeset import Ecto.Changeset
import Ecto.Query import Ecto.Query
alias LinkShortener.Accounts.User
schema "links" do schema "links" do
field :name, :string field :name, :string
field :url, :string field :url, :string
field :shorten, :string field :shorten, :string
belongs_to :user, User
timestamps() timestamps()
end end
@ -14,8 +17,8 @@ defmodule LinkShortener.Links.Link do
@doc false @doc false
def changeset(link, attrs) do def changeset(link, attrs) do
link link
|> cast(attrs, [:name, :url, :shorten]) |> cast(attrs, [:name, :url, :shorten, :user_id])
|> validate_required([:url, :shorten]) |> validate_required([:url, :shorten, :user_id])
|> unique_constraint(:shorten) |> unique_constraint(:shorten)
end end
end end

@ -0,0 +1,11 @@
defmodule LinkShortener.Repo.Migrations.AddRelationshipBetweenUsersAndLinks do
use Ecto.Migration
def change do
alter table(:links) do
add :user_id, references(:users, on_delete: :delete_all), null: false
end
create index(:links, [:user_id])
end
end
Loading…
Cancel
Save