Ecto schema dependent fields

This is really enforcing authorisation rules and you could do this in a number of spots depending on the overall design of your application.

It sounds like you would like to enforce it close to the database so probably the easiest approach is to add a custom changeset validation function (see Where to write custom changeset validation functions which rely on current database values / records? - #2 by idi527) or google “ecto custom validation”. You then need to ensure the appropriate changeset is used. The advantage of this approach over, say, enforcing through database layer logic is you can provide nice error messages and it plays nicely with Phoenix (dead views & liveview).

The disadvantage is that you will likely need permission-checking logic elsewhere anyway to avoid serving up an annoying user interface where the user thinks they’re doing the right thing until they get an error message telling them they could never have saved an article in the first place.

Personally I tend to handle authorisation concerns in a separate area and interrogate it from the UI and business contexts, but I’m working on an enterprisey application that has quite complex permissions models.

2 Likes