defmodule Jnb.Support.Ticket do use Ash.Resource, otp_app: :jnb, domain: Jnb.Support, data_layer: AshPostgres.DataLayer, notifiers: [Ash.Notifier.PubSub] postgres do table "tickets" repo Jnb.Repo end actions do defaults [:read] destroy :destroy do primary? true require_atomic? false # Clear the many-to-many relationship before destroying change before_action(fn changeset, _context -> case Ash.load(changeset.data, :team_relationships) do {:ok, ticket} -> # Delete all join table records Enum.each(ticket.team_relationships, fn rel -> Ash.destroy!(rel) end) changeset _ -> changeset end end) end create :create do accept [:title] primary? true argument :team_ids, {:array, :uuid}, allow_nil?: true change manage_relationship(:team_ids, :teams, type: :append_and_remove) end update :update do accept [:title] primary? true argument :team_ids, {:array, :uuid}, allow_nil?: true require_atomic? false change manage_relationship(:team_ids, :teams, type: :append_and_remove) end end pub_sub do module JnbWeb.Endpoint prefix "tickets" # This will publish all actions to a single topic "tickets" # with the action name as the event (e.g., "create", "update", "destroy") publish_all :create, "" publish_all :update, "" publish_all :destroy, "" end attributes do uuid_primary_key :id attribute :title, :string do allow_nil? false default "" public? true end timestamps() end relationships do has_many :team_relationships, Jnb.Support.TeamTicket do destination_attribute :ticket_id end many_to_many :teams, Jnb.Support.Team do join_relationship :team_relationships source_attribute_on_join_resource :ticket_id destination_attribute_on_join_resource :team_id end end aggregates do list :teams_ids, :teams, :id end end