Ash FrameworkAF
Ash Framework3y ago
16 replies
moissela

AshPhoenix Form use for `many_to_many` relationships through `append_and_remove` management

Hi all, and thanks for this amazing project!

Today I'm trying to figure out how to use AshPhoenix.Form with field of type {:array, :uuid}, for example in the context of managing a many_to_many relationships through append_and_remove, in extension of your example here https://hexdocs.pm/ash/2.6.18/managing-relationships.html.

For example, I have this resources with the desired result of allowing the user to select a list of tags from a multiple select:

defmodule Post do
use Ash.Resource, data_layer: AshPostgres.DataLayer

postgres do
table "posts"
repo Repo
end

attributes do
uuid_primary_key(:id)
attribute(:title, :string)
attribute(:content, :string)
end

relationships do
many_to_many :tags, Tag do
through PostTag
source_attribute_on_join_resource :post_id
destination_attribute_on_join_resource :tag_id
end
end

actions do
update :set_tags do
argument :tags, {:array, :uuid}

change manage_relationship(:tags, type: :append_and_remove)
end
end

defmodule Tag do
use Ash.Resource, data_layer: AshPostgres.DataLayer

postgres do
table "tags"
repo Repo
end

attributes do
uuid_primary_key(:id)
attribute(:name, :string)
end

relationships do
many_to_many :posts, Post do
through PostTag
source_attribute_on_join_resource :tag_id
destination_attribute_on_join_resource :post_id
end
end
end

defmodule PostTag do
use Ash.Resource, data_layer: AshPostgres.DataLayer

postgres do
table "post_tags"
repo Repo
end

attributes do
uuid_primary_key(:id)
end

relationships do
belongs_to :post, Post, allow_nil?: false
belongs_to :tag, Tag, allow_nil?: false, attribute_writable?: true
end
end

With this in place, how can I use AshPhoenix.Form auto-form and/or inputs_for for generating the post[tags][] fields in a clean way?
Was this page helpful?