Examples of using view models in Phoenix?

TLDR: Can you point me to writeups or examples of using “view models” in Phoenix apps?


I found myself getting confused using a single Ecto Schema to handle all of form validation, database constraints, translation of non-string Postgres values into form values, and so forth, so I’ve (roughly) adopted the old idea of “view models” to separate this:

vm1

… into this:

I’m tempted to write up my approach, but first I’d like to see what other people have done that’s similar. The basic idea of the view model pattern is that there’s one structure that represents the form, and it’s a different structure from the one that represents the row in the database.

(Do let me know if the writeup of those diagrams interests you. I mainly did them to learn OmniGraffle again after some years of not using it, so I’m not committed to write explanations around them.)

I’ve started doing that with liveview. Have an embedded_schema even defined in the liveview itself, which sole purpose is dealing with the html form.

2 Likes