How best to model partial updates of optional attributes?

The classic example is a "user settings" page, where if they only change their username but leave the password field blank, you want to not update the password, but instead ignore it. The best I can come up with is something like this:
update :update do
change prevent_change(:password), where: [absent(:password)]
end
update :update do
change prevent_change(:password), where: [absent(:password)]
end
Is there a better way to achieve this?
3 Replies
frankdugan3
frankdugan32y ago
I was just wondering the same thing, thinking about upcoming bulk updates in the context of a data-table where you select several rows and bulk update only the fields you change. :thinkies:
jart
jartOP2y ago
My use case is even more annoying because the actual attribute I'm updating is an embedded union type, so there's several ways you could define "blankness"
ZachDaniel
ZachDaniel2y ago
I would suggest adding arguments with the same name as the attribute, and then changing the attribute to the argument value only if the argument is present and meets some criteria. Alternatively, make it a UI concern. I.e the UI should only submit changed attributes. We could likely build something like this into AshPhoenix where it tracks each touched field. It has this built in, but currently all fields in a form are marked as touched because they are included in the payload. We could instead add a mode to validate where you provide the _target and it plucks out any fields that have been a _target…and maybe aren’t empty?

Did you find this page helpful?