dgraph_ex v0.1.5 DgraphEx.Changeset View Source
Link to this section Summary
Link to this section Functions
In cast/3
we do 3 things:
1) We ensure only changes to allowed fields “get through” by using Map.take/2.
2) We separate the model’s struct into it’s component parts: module and map.
3) We initialize the errors field to an empty list. And since only a changeset with an empty list is valid we ensure that a changeset has been instantiated outside cast/3 is not valid unless the errors field is set to an empty list.
In uncast/1 we first check to make sure that the errors field of the changeset is a list. If the errors field is not a list then this is not a valid changeset and an error is raised.
NOTE: A NON-LIST ERRORS FIELD IS NOT ALLOWED. USE CAST/3.
The errors field being a non-list indicates that there was an error in programming, not invalid input into a changes map. If you need to construct a Changeset struct outside cast/3 then ensure the errors field is set to a list upon instantiation.
After checking for a non-list errors field, we check is_valid?/1 which returns true only for empty
errors fields of changesets. If the Changeset is valid we apply each of the changes to the
model’s map and reconstruct the original struct with the changes applied, and return an
:ok tuple as in {:ok, model_struct_here}
. Finally, if the changeset was not valid we
return an :error tuple as in {:error, changeset_here}
.
This should be the final function called for a chain of changeset functions (such as validators).