EctoAutoslugField

Build StatusCoverage StatusHex VersionLicense

ecto_autoslug_field is a reusable Ecto library which can automatically create slugs from other fields.

This library internally uses slugger as it's default slug-engine.

You can find the full documentation online: docs.

Installation

def deps do
  # installation via hex (version 0.3 and onwards only supports `{:ecto, ">= 2.1"}`):
  [{:ecto_autoslug_field, "~> 0.3"}]

  # if you want to use github:
  # [{:ecto_autoslug_field, github: "sobolevn/ecto_autoslug_field"}]

  # if you need support for `{:ecto, "~> 2.0"}`:
  # [{:ecto_autoslug_field, "~> 0.2"}]

  # if you need support for older Ecto versions (< 2.0):
  # [{:ecto_autoslug_field, "~> 0.1.3"}]
end

Options

There are several options to configure.

Required:

Optional:

Functions

Examples

The simplest example:

defmodule EctoSlugs.Blog.Article.TitleSlug do
  use EctoAutoslugField.Slug, from: :title, to: :slug
end

defmodule EctoSlugs.Blog.Article do
  use Ecto.Schema
  import Ecto.Changeset
  alias EctoSlugs.Blog.Article
  alias EctoSlugs.Blog.Article.TitleSlug

  schema "blog_articles" do
    field :breaking, :boolean, default: false
    field :content, :string
    field :title, :string

    field :slug, TitleSlug.Type

    timestamps()
  end

  def changeset(%Article{} = article, attrs) do
    article
    |> cast(attrs, [:title, :content, :breaking])
    |> validate_required([:title, :content])
    |> unique_constraint(:title)
    |> TitleSlug.maybe_generate_slug
    |> TitleSlug.unique_constraint
  end
end

More complex examples are covered in this tutorial.

Changelog

See CHANGELOG.md.

License

MIT. Please see LICENSE.md for licensing details.