Polymorphic Embedded Resources?
Is it possible to have embedded resources be one or more structs
for example
Thinking either this is not supported or could be done with some sort of custom type?
10 Replies
You can use the built in Union type
attribute :attribute, :union, constraints: [types: …]
Awesome thanks! What’s the form interop story with union types?
Oh, honestly…it’s just not been handled yet
You’re probably going to have to roll your own on that front for now
🫡
You can still iterate over the values using AshPhoenix.Form.value and all that, and you can use AshPhoenix.Form.update_form to do things like add/remove(if it’s a list). If it’s not then this is probably not too difficult
Grabbing the value of the union type returns an Ash.Resource struct. Are you thinking to then feed that in to an additional
AshPhoenix.Form.for_update
? My first thought was to implement it similar to multi-step forms where changing the tag value changed the nested form , but I haven't made one of those yet so thats all in theory🤔 I think you might need to like extract the values yourself instead of using
AshPhoenix.Form
. Just vanilla form stuff.@Zach Daniel sorry to dig up an old post, but what's the lowest-pain way of doing this? I'm trying to do something similar where a resource has an embedded resource which could be 1 of ~5 types. The types are fairly complex (they each represent external API data from a different provider)
Will a union type cause more headaches than, say, having 5 attributes; leaving them all nil except for the one that matches the type we want to use.
I'm aiming for an easy story for things like validations and form editing.
A union is the way to go 👍
AshPhoenix.Form knows how to handle them now