Ecto validating a struct

Hi,

So I have the following situation:

I have an schema for a Class, which contains a number of Topic schemas and a single ClassDetails schema. The idea is that the user can populate this data over a period of time, adding to it incrementally. During this time I am more lax with some of the requirements, for example - each topic doesn’t need it’s description filling in before it is saved to the database (so it is not included in the validate_required list)

However, when I come to publish this Class these restrictions need to be enforced. So I would like to take the Class struct which I have just loaded from the database and ideally run a recursive “validate_for_publishing” function.

The way I envisage this is each schema having it’s own “validate_for_publishing” function and then I can simply call Class.validate_for_publishing(loaded_class).

Is there some functionality in Ecto changesets which would facilitate this? It would be nice to use existing functionality like “validate_required” and rely on Ecto’s behavior of aggregating validation errors when casting/validating maps -> structs.

Or is this something I would need to implement fully myself?

Thanks,
James

So I ended up rolling my own thing.

I added module functions which looked like:

def validate_for_X({errors, class} = validation) do
   validation
   |> not_empty(:name)
   |> validate_child(:lesson, &Lesson.validate_for_x/1)
end

Simple, but it works.

1 Like