Polymorphic Embedded Resources?

Is it possible to have embedded resources be one or more structs for example
defmodule MainResource do
use AshResource, data_layer: :embedded

attributes do
attribute :some_resource, ResourceB || ResourceA
end
defmodule MainResource do
use AshResource, data_layer: :embedded

attributes do
attribute :some_resource, ResourceB || ResourceA
end
Thinking either this is not supported or could be done with some sort of custom type?
10 Replies
ZachDaniel
ZachDaniel2y ago
You can use the built in Union type attribute :attribute, :union, constraints: [types: …]
ZachDaniel
ZachDaniel2y ago
Ash HQ
Module: Ash.Type.Union
View the documentation for Ash.Type.Union on Ash HQ.
gvanders
gvanders2y ago
Awesome thanks! What’s the form interop story with union types?
ZachDaniel
ZachDaniel2y ago
Oh, honestly…it’s just not been handled yet You’re probably going to have to roll your own on that front for now
gvanders
gvandersOP2y ago
🫡
ZachDaniel
ZachDaniel2y ago
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
gvanders
gvandersOP2y ago
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
ZachDaniel
ZachDaniel2y ago
🤔 I think you might need to like extract the values yourself instead of using AshPhoenix.Form. Just vanilla form stuff.
Alex Slade
Alex Slade9mo ago
@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.
ZachDaniel
ZachDaniel9mo ago
A union is the way to go 👍 AshPhoenix.Form knows how to handle them now

Did you find this page helpful?