Last active
August 1, 2022 16:03
-
-
Save char0n/6fca76e886a2cfbd3aaa05526f287728 to your computer and use it in GitHub Desktop.
Model example how to use Ecto to validate nested JSON data in you API payloads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ApiDataStructure do | |
defmodule User do | |
use Ecto.Schema | |
import Ecto.Changeset | |
alias ApiDataStructure.Profile | |
embedded_schema do | |
field :username, :string | |
field :email, :string | |
embeds_one :profile, Profile | |
end | |
def changeset(user, attrs) do | |
user | |
|> cast(attrs, [:username, :email]) | |
|> cast_embed(:profile, with: &Profile.changeset/2, required: true) | |
|> validate_required([:username, :email]) | |
end | |
end | |
defmodule Profile do | |
use Ecto.Schema | |
import Ecto.Changeset | |
embedded_schema do | |
field :timezone, :string | |
end | |
def changeset(profile, attrs) do | |
profile | |
|> cast(attrs, [:timezone]) | |
|> validate_required([:timezone]) | |
end | |
end | |
end | |
# Run the following code in iex: | |
# ApiDataStructure.User.changeset(%ApiDataStructure.User{}, %{username: "char0n", email: "[email protected]", profile: %{timezone: "Europe/Prague"}}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment