Adzz
Casting Sugar - Announcing EctoMorph, a lib to help casting between structs for Ecto
Ecto is great, we use it for validations. But validating different embeds can quickly get confusing, and there are some ways I found it a bit cumbersome.
I’ve created a lib to help add some sugar to what Ecto does, we’ve been using it in prod and it has been going well so far. Some examples, say you have a schema like this:
defmodule Embed do
use Ecto.Schema
embedded_schema do
field(:bar, :string)
end
end
defmodule Test do
use Ecto.Schema
embedded_schema do
field(:thing, :string)
embeds_one(:embed, Embed)
end
end
Usually you would have to do this:
Ecto.Changeset.cast(%Test{}, %{"thing" => "foo", "embed" => %{"bar"=> "baz"}}, [:thing])
|> Ecto.Changeset.cast_embed(:embed)
With EctoMorph you can do this:
EctoMorph.to_struct(%{"thing" => "foo", "embed" => %{"bar"=> "baz"}}, Test)
I would love feedback on whether people think this is useful, or feature requests!
Repo: GitHub - Adzz/ecto_morph: morph your Ecto capabilities into the s t r a t o s p h e r e ! · GitHub
I went into more detail here: https://medium.com/@ItizAdz/ecto-cast-ing-sugar-31bddbc62cd7
Most Liked
Adzz
Just by way of a feature update here are some of the things that are now available with ecto_morph:
- Bug fix: We now ignore through associations when casting or generating changesets. Those kinds of associations are readonly anyway, so we just ensure we don’t error.
- to_struct has been renamed to
cast_to_struct. - You can specify a list of fields to filter the changes by, like in ecto, but this is recursive like so:
%{comments: [%{like: %{count: 10, ignored: "okay"}}}]}
|> EctoMorph.cast_to_struct(Post, [comments: [like: :count]])
You can now validate nested relations
json = %{
"has_many" => [
%{"steamed_hams" => [%{"pickles" => 1}, %{"pickles" => 2}]},
%{"steamed_hams" => [%{"pickles" => 1}]},
%{"steamed_hams" => [%{"pickles" => 4}, %{"pickles" => 5}]}
]
}
# Here each of the steamed_hams above will have their pickle count validated:
EctoMorph.generate_changeset(json, MySchema)
|> EctoMorph.validate_nested_changeset([:has_many, :steamed_hams], fn changeset ->
changeset
|> Ecto.Changeset.validate_number(:pickles, greater_than: 3)
end)
Popular in Announcing
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








