Does Ash supports polymorphic embedded resources?

The title says it all, is it possible to create more than one embedded resource and use them both as a single attribute in a third resource?

I was thinking about something similar to what this library does for ecto: Polymorphic embeds for Ecto — Polymorphic Embed v3.0.5

2 Likes

Yes :slight_smile:

defmodule YourEmbed do
  ...
end


defmodule YourOtherEmbed do
  ...
end
attribute :one_or_the_other, :union do
  constraints types: [
    one: [type: YourEmbed],
    other: [type: YourOtherEmbed]
  ]
end

You can also extract that out into a NewType

defmodule OneOrTheOther do
  use Ash.Type.NewType, subtype_of: :union, constraints: [
    types: [
      one: [type: YourEmbed],
      other: [type: YourOtherEmbed]
    ]
  ]
end

Then you can use the type like so:

attribute :one_or_the_other, OneOrTheOther

Check the docs for unions, as you may want some of the additional tools around it, like tag and tag_value to configure a type field and the value it should equal for it to be considered one type or the other.

The union type can also be used with primitives.

6 Likes