EctoAutoslugField - automatically create slugs from other fields

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.

Examples

The first use case is the simplest one. When an article is created, generate a slug from it’s title. Do nothing more.

defmodule EctoSlugs.Blog.Article.TitleSlug do
  @moduledoc """
  This module represents slug build from :title field.

  This module uses `:title` field to update `:slug` field on slug save.
  """

  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  # using the module created above

    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  # creating slug if does not exist
    |> TitleSlug.unique_constraint  # validating that it is unique
  end
end

Tutorial

Full tutorial is available online: https://medium.com/wemake-services/creating-slugs-for-ecto-schemas-7349513410f0

2 Likes