Auto generate a slug

I have the following attributes and would like to autogenerate a slug from the name. Until now I always used https://github.com/wemake-services/ecto_autoslug_field to do this. What is the ash way to solve this? attributes do uuid_primary_key :id attribute :name, :string attribute :slug, :string end
GitHub
GitHub - wemake-services/ecto_autoslug_field: Automatically create ...
Automatically create slugs for Ecto schemas. Contribute to wemake-services/ecto_autoslug_field development by creating an account on GitHub.
3 Replies
ZachDaniel
ZachDaniel•3y ago
What you'd want to do is add a "global change", which is done using the top level changes DSL. You'd want to do something like this.
changes do
change fn changeset, _ ->
if Ash.Changeset.changing_attribute?(changeset, :field) do
value = Ash.Changeset.get_attribute(changeset, :slug, :field)
Ash.Changeset.force_change_attribute(changeset, make_slug(value))
else
changeset
end
end
end
changes do
change fn changeset, _ ->
if Ash.Changeset.changing_attribute?(changeset, :field) do
value = Ash.Changeset.get_attribute(changeset, :slug, :field)
Ash.Changeset.force_change_attribute(changeset, make_slug(value))
else
changeset
end
end
end
And if you want to make it reusable, define your change in a module, and provide opts like so:
defmodule MakeSlug do
use Ash.Resource.Change

def changeset(changeset, opts, _context) do
field = opts[:fields]
slug = opts[:slug]
if Ash.Changeset.changing_attribute?(changeset, field) do
value = Ash.Changeset.get_attribute(changeset, field)
Ash.Changeset.force_change_attribute(changeset, slug, make_slug(value))
else
changeset
end
end
end
defmodule MakeSlug do
use Ash.Resource.Change

def changeset(changeset, opts, _context) do
field = opts[:fields]
slug = opts[:slug]
if Ash.Changeset.changing_attribute?(changeset, field) do
value = Ash.Changeset.get_attribute(changeset, field)
Ash.Changeset.force_change_attribute(changeset, slug, make_slug(value))
else
changeset
end
end
end
So then you can do change {MakeSlug, field: :field, slug: :slug}
Stefan Wintermeyer
Stefan WintermeyerOP•3y ago
Thanks!
ZachDaniel
ZachDaniel•3y ago
If your question/issue has been resolved, please close the forum post and add the "resolved" tag. Thanks for using the new forum system, hopefully this was and continues to be a good experience 🙂

Did you find this page helpful?