TestPhoenixLiveView/lib/test_phoenix_live_view/messaging/message.ex
2024-02-15 21:46:14 +01:00

33 lines
695 B
Elixir

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