Ecto Custom Field Setting

How to set a custom field in ecto changeset pipelines

# declare this in your schema file
defp slugify(changeset, from_field, to_field, options \\ []) do
  case Map.get(changeset.changes, from_field) do
    nil -> changeset
    str -> put_change(changeset, to_field, Slug.slugify(str, options))
  end
end

# use it like this
# ...
changeset
|> slugify(:name, :slug)
# ...

Instead of passing everything as attrs from the outside, you can modify data fields during changeset casting. In this example, the slugify library is used to automatically generate a slug field from a name field, but only if the changeset wants to actually change the name field.

Technologies: