Create slugs from Ecto fields automatically
- Install https://github.com/sobolevn/ecto_autoslug_field
- 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
Written by sobolevn
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Elixir
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#