Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

ecto-changesets

БесплатноБез исполняемых скриптовНе проверен

Use when validating and casting data with Ecto changesets including field validation, constraints, nested changesets, and data transformation. Use for…

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

Ecto Changesets

Master Ecto changesets to validate, cast, and transform data before database operations. This skill covers changeset creation, validation, constraints, handling associations, and advanced patterns for maintaining data integrity.

Basic Changeset

defmodule MyApp.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :name, :string
    field :email, :string
    field :age, :integer

    timestamps()
  end

  def changeset(user, params \\ %{}) do
    user
    |> cast(params, [:name, :email, :age])
    |> validate_required([:name, :email])
  end
end

# Usage
changeset = MyApp.User.changeset(%MyApp.User{}, %{name: "John", email: "[email protected]"})

Changesets filter and validate parameters before they're applied to a struct. The cast/3 function specifies which fields can be changed, and validate_required/2 ensures specific fields are present.

Creating and Validating Changesets

defmodule MyApp.Person do
  use Ecto.Schema
  import Ecto.Changeset

  schema "people" do
    field :first_name, :string
    field :last_name, :string
    field :age, :integer

    timestamps()
  end

  def changeset(person, params \\ %{}) do
    person
    |> cast(params, [:first_name, :last_name, :age])
    |> validate_required([:first_name, :last_name])
    |> validate_number(:age, greater_than_or_equal_to: 0)
  end
end

# Create changeset
changeset = MyApp.Person.changeset(%MyApp.Person{}, %{first_name: "Jane"})

# Check validity
changeset.valid?  # false, last_name is missing

# Access errors
changeset.errors
# [first_name: {"can't be blank", [validation: :required]},
#  last_name: {"can't be blank", [validation: :required]}]

The valid? field indicates whether the changeset has any errors. The errors field contains a keyword list of validation failures with error messages and metadata.

Inserting with Changesets

person = %MyApp.Person{}
changeset = MyApp.Person.changeset(person, %{
  first_name: "John",
  last_name: "Doe",
  age: 30
})

case MyApp.Repo.insert(changeset) do
  {:ok, person} ->
    # Successfully inserted
    IO.puts("Created person with ID: #{person.id}")

  {:error, changeset} ->
    # Validation or constraint errors
    IO.inspect(changeset.errors)
end

The Repo.insert/1 function accepts a changeset and returns {:ok, struct} on success or {:error, changeset} on failure. Pattern matching makes error handling straightforward.

Updating with Changesets

person = MyApp.Repo.get!(MyApp.Person, 1)
changeset = MyApp.Person.changeset(person, %{age: 31})

case MyApp.Repo.update(changeset) do
  {:ok, updated_person} ->
    # Successfully updated
    IO.puts("Updated person age to: #{updated_person.age}")

  {:error, changeset} ->
    # Validation or constraint errors
    IO.inspect(changeset.errors)
end

Updates work similarly to inserts, but start with an existing struct from the database. The changeset tracks which fields have changed.

Type Casting

changeset = Ecto.Changeset.cast(%MyApp.User{}, %{"age" => "25"}, [:age])
user = MyApp.Repo.insert!(changeset)
user.age  # 25 (integer, not string)

The cast/3 function automatically converts parameter values to their schema-defined types. Strings like "25" are converted to integers when the field type is :integer.

Field Validations

defmodule MyApp.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :email, :string
    field :username, :string
    field :age, :integer
    field :bio, :string
    field :website, :string

    timestamps()
  end

  def changeset(user, params \\ %{}) do
    user
    |> cast(params, [:email, :username, :age, :bio, :website])
    |> validate_required([:email, :username])
    |> validate_format(:email, ~r/@/)
    |> validate_length(:username, min: 3, max: 20)
    |> validate_length(:bio, max: 500)
    |> validate_number(:age, greater_than: 0, less_than: 150)
    |> validate_inclusion(:age, 18..100)
    |> validate_format(:website, ~r/^https?:\/\//)
  end
end

Ecto provides many built-in validators including validate_format/3 for regex patterns, validate_length/3 for string lengths, validate_number/3 for numeric constraints, and validate_inclusion/3 for allowed values.

Custom Validation Functions

defmodule MyApp.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :email, :string
    field :password, :string, virtual: true
    field :password_hash, :string

    timestamps()
  end

  def changeset(user, params \\ %{}) do
    user
    |> cast(params, [:email, :password])
    |> validate_required([:email, :password])
    |> validate_email_format()
    |> validate_password_strength()
    |> hash_password()
  end

  defp validate_email_format(changeset) do
    changeset
    |> validate_format(:email, ~r/@/, message: "must be a valid email")
    |> validate_length(:email, max: 255)
  end

  defp validate_passwor
Полный SKILL.md на GitHub

Установить ecto-changesets в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Bash
Read

FAQ

Что делает скилл ecto-changesets?

Use when validating and casting data with Ecto changesets including field validation, constraints, nested changesets, and data transformation. Use for ensuring data integrity before database operations.

Как установить скилл ecto-changesets?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл ecto-changesets запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить ecto-changesets с