Begin add message
This commit is contained in:
parent
e0f052b653
commit
8bbc8b5ebf
2 changed files with 47 additions and 0 deletions
33
lib/test_phoenix_live_view/messaging/message.ex
Normal file
33
lib/test_phoenix_live_view/messaging/message.ex
Normal 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
|
14
priv/repo/migrations/20240215202227_create_messages.exs
Normal file
14
priv/repo/migrations/20240215202227_create_messages.exs
Normal 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
|
Loading…
Reference in a new issue