Hi all folks!
In the last few days I was trying to make my embedded schema fields dynamic. What I mean is that I’ve got a User model that embeds_one profile:
defmodule MyApp.User do
schema "users" do
field :email
field :status
...
embeds_one :profile, MyApp.Profile
end
end
and
defmodule MyApp.Profile do
embedded_schema do
field :first_name
field :last_name
...
end
Everything works fine with static embedded fields declaration, but what about dynamic fields?
If I would inject Profile
fields dinamically say by using a configuration like this:
[
%{
name: "first_name",
data_type: "string",
rule_type: "required",
default: ""
},
%{
name: "last_name",
data_type: "string",
rule_type: "required",
default: ""
},
%{
name: "fiscal_code",
data_type: "string",
rule_type: "required",
default: ""
},
%{
name: "date_of_birth",
data_type: "string",
rule_type: "optional",
default: ""
}
]
I can use a simple field :profile
into User
model instead of embeds_one :profile
and remove embedded_schema
entirely in Profile
model and use cast to validate
{data_value, data_type}
|> cast(params, Map.keys(data_type))
...
So good so far but I cannot use cast_embed
validation on User
model anymore like this:
struct
|> changeset(params)
|> cast_embed(:profile, required: true, with: &MyApp.Profile.registration_changeset/2)
cause cast_embed
and put_embed
is expecting an embedded static
schema.
Is there an alternative way to validate User
and Profile
models using dynamic fields?
Thanks for your help