From 8bbc8b5ebf9dedd211ef6c027e551a686963020d Mon Sep 17 00:00:00 2001 From: Florian RICHER Date: Thu, 15 Feb 2024 21:46:14 +0100 Subject: [PATCH] Begin add message --- .../messaging/message.ex | 33 +++++++++++++++++++ .../20240215202227_create_messages.exs | 14 ++++++++ 2 files changed, 47 insertions(+) create mode 100644 lib/test_phoenix_live_view/messaging/message.ex create mode 100644 priv/repo/migrations/20240215202227_create_messages.exs diff --git a/lib/test_phoenix_live_view/messaging/message.ex b/lib/test_phoenix_live_view/messaging/message.ex new file mode 100644 index 0000000..b68be57 --- /dev/null +++ b/lib/test_phoenix_live_view/messaging/message.ex @@ -0,0 +1,33 @@ +defmodule TestPhoenixLiveView.Messaging.Message do + use Ecto.Schema + import Ecto.Changeset + + schema "messages" do + field :message, :string + belongs_to :user, TestPhoenixLiveView.Accounts.User + + timestamps(type: :utc_datetime) + end + + @doc false + def changeset(message, attrs) do + message + |> cast(attrs, [:user_id, :message]) + |> validate_message + |> validate_user + end + + @doc false + def validate_message(changeset) do + changeset + |> validate_required([:message]) + |> validate_length(:message, max: 160) + end + + @doc false + def validate_user(changeset) do + changeset + |> validate_required(:user_id) + |> foreign_key_constraint(:user_id) + end +end diff --git a/priv/repo/migrations/20240215202227_create_messages.exs b/priv/repo/migrations/20240215202227_create_messages.exs new file mode 100644 index 0000000..c9393f6 --- /dev/null +++ b/priv/repo/migrations/20240215202227_create_messages.exs @@ -0,0 +1,14 @@ +defmodule TestPhoenixLiveView.Repo.Migrations.CreateMessages do + use Ecto.Migration + + def change do + create table(:messages) do + add :message, :text + add :user_id, references(:users, on_delete: :delete_all), null: false + + timestamps(type: :utc_datetime) + end + + create index(:messages, [:user_id]) + end +end