Hi! I am trying to figure out if it is possible to have have embedded field as a struct with empty/default values if the embedded field in params is nil.
So let’s say I have two embedded schemas like this.
defmodule EmbedSchema do
use Ecto.Schema
import Ecto.Changeset
embedded_schema do
field(:good_subfield)
field(:pretty_subfield)
end
def changeset(schema, params) do
schema
|> cast(params, [:good_subfield, :pretty_subfield])
end
end
defmodule ParentSchema do
use Ecto.Schema
import Ecto.Changeset
embedded_schema do
field(:a_field)
embeds_one(:embed_field, EmbedSchema)
end
def new(params) do
%__MODULE__{}
|> cast(params, [:a_field])
|> cast_embed(:embed_field)
|> apply_changes()
end
end
No, but I got another idea, but maybe there is a better way to solve this. So my next idea is instead of doing cast_embed/3 I do put_embed/4. So I filter out fields with nil and then create embed fields by either passing value from params or default to %{}. Though I am not sure this is the best way to go about this.
I think this is actually fine, the code works as I want it to, why I’m using Ecto and embedded schema is to get some additional validation over using plain structs, as I want to also be sure that the nested fields are always there. Anyway, thanks a lot for your replies!