Ash FrameworkAF
Ash Framework3y ago
13 replies
Stefan Wintermeyer

add_tag but unique

A product has a many_to_many relationship to a tag (via a product_tag resource).

lib/app/shop/resources/product.ex
    [...]
    create :create do
      primary? true
      argument :tags, {:array, :map}

      argument :add_tag, :map do
        allow_nil? false
      end

      change manage_relationship(:tags, type: :append_and_remove, on_no_match: :create)
      change manage_relationship(:add_tag, :tags, type: :create)
    end
    [...]


This works nicely:

iex(6)> banana = App.Shop.Product.create!(%{name: "Banana", add_tag: %{name: "Yellow"}})


Unfortunately I can also add another "Yellow" tag via an update:

iex(7)> App.Shop.Product.update!(banana, %{add_tag: %{name: "Yellow"}}).tags |> Enum.map(& &1.name)
["Yellow", "Yellow"]


Obviously this should not happen. The "Yellow" tag should be unique.

The longer I think about this the lesser I know how to solve it. Should I through a validation error? How can I do this? Should I just OK it but not adding another tag? How would I do that?
Was this page helpful?