Optional argument with defaults for actions
It feels like it should be something really simple but its just not working out.
I have a resource with a non-null string attribute that defaults to an empty string
Then how can I get the action to accept an optional argument for title, defaulting to an empty string?
Something like this:
Will raise an error telling me
title
is required. And something like this
somehow still raises with the same changeset error. I feel like I'm missing something really obvious 😓5 Replies
turns out empty string as argument will evalulate to nil.
i.e.
This will work and correctly set title attribute to "a"
here title attribute will remain as
nil
I suspect this is here to help translating empty form values to nil
.Hey James - You're likely looking for
allow_nil_input
on the create action. https://hexdocs.pm/ash/dsl-ash-resource.html#actions-create-allow_nil_input
This allows you to have an attribute be allow_nil? false
, but make it optionalSolution
You can also
constraints: [allow_empty?: true]
i.e
attribute :title, :string, constraints: [allow_empty?: true, trim?: false]
skips the standard sanitization we do to trim whitespace around the value and then turn ""
-> nil
I was just about the say that even with
allow_nil_input?
the action will fail due to sanitization but the constraint to skip sanitization works like a charm. Thank you Chaz and Zach! 😄