Ash FrameworkAF
Ash Framework3y ago
5 replies
morfertaw

Understanding "manage_relationship"

So I have a many_to_many relationship between the following resources.

Reactant

defmodule Flame.App.Resources.Reactant do
...
  attributes do
    ...
    attribute :identity, :string do
      allow_nil? false
      constraints trim?: false, max_length: 20, min_length: 4, allow_empty?: false
    end
    ...
  end

  actions do
    defaults [:create, :read, :update, :destroy]

    create :define do
      upsert? true

      argument :source_definitions, {:array, :map}

      change manage_relationship(:source_definitions, :sources,
               on_lookup: :relate,
               on_no_match: :create,
               on_match: :update,
               on_missing: :unrelate
             )
    end

    update :redefine do
      argument :source_definitions, {:array, :map}

      change manage_relationship(:source_definitions, :sources,
               on_lookup: :relate,
               on_match: :update,
               on_no_match: :create,
               on_missing: :unrelate
             )
    end
  end

  relationships do
    many_to_many :sources, Flame.App.Resources.Source do
      through Flame.App.Resources.ReactantSource
      source_attribute_on_join_resource :reactant_id
      destination_attribute_on_join_resource :source_id
    end
  end
...
end

Source

defmodule Flame.App.Resources.Source do
...
  attributes do
    uuid_primary_key :id

    attribute :description, :string do
      allow_nil? false
    end

    create_timestamp :created_at
    update_timestamp :updated_at
  end

  actions do
    defaults [:create, :read, :update, :destroy]
  end

  identities do
    identity :unique_description, [:description]
  end
...
end
Was this page helpful?