Add a relationship between a user and links.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user