Begin add message

This commit is contained in:
Florian RICHER 2024-02-15 21:46:14 +01:00
parent e0f052b653
commit 8bbc8b5ebf
2 changed files with 47 additions and 0 deletions

View file

@ -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

View file

@ -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