Override resource field before validation
I have a slug field that is based on a name. I want to be able to set it from title by something like slugify in Django. But I'm not able to override
nil
values of fields before they get validated in create action. I've used change
but it is not called when slug is nil
. I don't want to do it before calling create action because it just doesn't feel right and dry. If I enable this action through an API and web interface than it will be 2 places to convert title to slug.
In case you don't know what slug is, here's wikipedia article. https://en.wikipedia.org/wiki/Slug_%28publishing%29 It is used in URL to uniquely identify a resource and this term comes from publishing. URL safe title is not fast to write is it? Django is my background where this term is frequently used.Slug (publishing)
In newspaper editing, a slug is a short name given to an article that is in production. The story is labeled with its slug as it makes its way from the reporter through the editorial process. The AP Stylebook prescribes its use by wire reporters (in a "keyword slugline") as follows: "The keyword or slug (sometimes more than one word) clearly ind...
1 Reply
There are two general patterns for this is:
1: use
allow_nil_input
this says “normally this is required, but something in the action will set it if it’s not set”
2. use an explicit accept list (or reject if you want). Use this if you never want the slug to be set by the user. By default, all public writable attributes are accepted by an action. This will change in 3.0 to default to no actions.
Bonus 3.) if the attribute is never writable by the user explicitly, mark the attribute as writable? false
. Then in your change where you set the slug, use Ash.Changeset.force_change_attribute/3
The point being that if a given attribute is not accepted by an action, or is not writable, or is in allow_nil_input
then it gets validated just prior to actually inserting