Last Updated: September 28, 2016
·
702
· sobolevn

Create slugs from Ecto fields automatically

  1. Install https://github.com/sobolevn/ecto_autoslug_field
  2. Then:
defmodule NameSlug do
  use EctoAutoslugField.Slug, from: :name, to: :slug
end

defmodule User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :name, :string
    field :slug, NameSlug.Type
  end

  @required_fields ~w(name)
  @optional_fields ~w(slug)

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> NameSlug.maybe_generate_slug
    |> NameSlug.unique_constraint
  end
end