Ecto Custom Field Setting
Elixir Snippet: How to set a custom field in ecto changeset pipelines based on previous data fields.
# 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.
Linked Technologies
What it's made of
Ecto
A toolkit for data mapping and language integrated query. The Elixir answer to Ruby's ActiveRecord.
Elixir
Harness the power of concurrent, fault-tolerant programming for scalable, maintainable applications. Code that flows like water!
Linked Categories
Where it's useful
Data Engineering
Explore the essentials of Data Engineering, delving into how data systems are built and maintained. From organizing data flows to automating complex data processes, discover the tools and techniques that make data easily accessible and useful for everyday projects and insights.