📎 Webclip
(Ab)using Ecto as Elixir data casting and validation library
The article argues that Ecto can be used as a general-purpose casting and validation layer, not only as a database access library. It starts from the usual schema-backed pattern, then shifts to tableless forms and service modules that accept user input, validate it, and either return errors or proceed with business logic.
Reading notes#
- Ecto changesets can be used without
Ecto.Schema, so casting and validations are available for use cases beyond database tables. - A changeset represents the changes made from submitted params against an existing struct, and it only tracks fields that were actually changed.
- In a schema-backed example,
App.User.changeset/2castsfull_nameandemail, validates required fields, and returns a changeset that can be inserted or updated throughRepo. - Validation errors are not rendered automatically unless the changeset has an
actionset, which can happen throughRepo.insert,Repo.update, orapply_action/2. - For a contact form, the controller can call a custom service module instead of
Repo.insert, and the service returns:okon success or{:error, changeset}on failure. - The service module casts params against a schema map, validates required fields and checkbox acceptance, and uses
apply_action(:insert)to turn valid params into typed data. - The form template uses Phoenix form helpers with the changeset so it can show field errors when required values are missing.
- An update shows how
embedded_schemacan replace the earlier tableless pattern. - The article ends by extracting the shared casting and validation behavior into an
App.Servicemacro so individual services only define schema, validations, and business logic.
