Adzz / ecto_morph

morph your Ecto capabilities into the s t r a t o s p h e r e !
Apache License 2.0
109 stars 8 forks source link

Add a required: true for nested relations #41

Closed Adzz closed 3 years ago

Adzz commented 3 years ago

This should work for generate_changeset and cast_to_struct really. It allows a user to cast to a struct, marking a relation as required on the way.

although now you could do:

EctoMorph.generate_changeset(%{stu: :ff}, %Struct{})
|> Ecto.Changeset.validate_required([:relation])
|> EctoMorph.validate_nested_changeset([:relation], &Struct.validate_create/1)

Adding it to the top level of cast_to_struct means we could:

EctoMorph.cast_to_struct(%{stu: :ff}, %Struct{}, [:relation])

and have it fail if / when :relation is missing. Though not sure what the API should look like really.

Adzz commented 3 years ago

On reflection I wonder if a better way is to always have it optional on cast, and just have a validation for relations like so:

EctoMorph.generate_changeset(...)
|> EctoMorph.validate_required([my_relation: [:a_field, :another_one]])
|> EctoMorph.into_struct!()