diff --git a/lib/link_shortener/accounts/user.ex b/lib/link_shortener/accounts/user.ex index fe75a8a..0ab55d8 100644 --- a/lib/link_shortener/accounts/user.ex +++ b/lib/link_shortener/accounts/user.ex @@ -2,12 +2,15 @@ defmodule LinkShortener.Accounts.User do use Ecto.Schema import Ecto.Changeset + alias LinkShortener.Links.Link + schema "users" do field :email, :string field :password, :string, virtual: true, redact: true field :hashed_password, :string, redact: true field :current_password, :string, virtual: true, redact: true field :confirmed_at, :utc_datetime + has_many :links, Link timestamps(type: :utc_datetime) end diff --git a/lib/link_shortener/links/link.ex b/lib/link_shortener/links/link.ex index a3844ee..8d33e58 100644 --- a/lib/link_shortener/links/link.ex +++ b/lib/link_shortener/links/link.ex @@ -3,10 +3,13 @@ defmodule LinkShortener.Links.Link do import Ecto.Changeset import Ecto.Query + alias LinkShortener.Accounts.User + schema "links" do field :name, :string field :url, :string field :shorten, :string + belongs_to :user, User timestamps() end @@ -14,8 +17,8 @@ defmodule LinkShortener.Links.Link do @doc false def changeset(link, attrs) do link - |> cast(attrs, [:name, :url, :shorten]) - |> validate_required([:url, :shorten]) + |> cast(attrs, [:name, :url, :shorten, :user_id]) + |> validate_required([:url, :shorten, :user_id]) |> unique_constraint(:shorten) end end diff --git a/priv/repo/migrations/20240901105600_add_relationship_between_users_and_links.exs b/priv/repo/migrations/20240901105600_add_relationship_between_users_and_links.exs new file mode 100644 index 0000000..80c605b --- /dev/null +++ b/priv/repo/migrations/20240901105600_add_relationship_between_users_and_links.exs @@ -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