XUtils

ecto_autoslug_field

Automatically creates slugs for your Ecto models.


Options

There are several options to configure.

Required:

  • :to - represents the slug field name where to save value to

Optional:

  • :from - represents the source fields from which to build slug, if this option is not set you have to override get_sources/2 function
  • :always_change - if this option is set slug will be recreated from the given sources each time maybe_generate_slug function is called

Functions

  • get_sources/2 - this function is used to get sources for the slug, docs.
  • build_slug/2 - this function is a place to modify the result slug, docs.

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(model, params \\ :invalid) do
    model
    |> cast(params, [:title, :content, :breaking])
    |> validate_required([:title, :content])
    |> unique_constraint(:title)
    |> TitleSlug.maybe_generate_slug()
    |> TitleSlug.unique_constraint()
  end
end

See this tutorial for some more examples.

Changelog

See CHANGELOG.md.


Articles

  • coming soon...