Hi,
Say I have the following resource which has a field :parent
which references the same resource (allow_nil = true). What I want to generate is a field called path which recursively follows each parent and returns a list of each resource’s slug until parent is empty. This represents a hierarchy:
e.g
id =1, name=Sport, slug=sport,parent_id=null
id=2, name=Local Sport, slug=local-sport,parent_id=1
id=3, name=Soccer, slug=soccer,parent_id=2
For each resource I want to generate a path
field such that
id =1, name=Sport, slug=sport,parent_id=null, path=[‘sport’]
id=2, name=Local Sport, slug=local-sport,parent_id=1, path=[‘sport’, ‘local-sport’]
id=3, name=Soccer, slug=soccer,parent_id=2, path=[‘sport’, ‘local-sport’, ‘soccer’]
Could someone assist me in heading in the right direction? I’m looking at calculations vs aggregates and im not too sure which of these are the right choice for this. Furthermore I’m not very certain on how to define such a recursive query
defmodule ContentCove.Articles.Topic do
use Ash.Resource,
otp_app: :content_cove,
domain: ContentCove.Articles,
data_layer: AshPostgres.DataLayer,
extensions: [AshAdmin.Resource]
postgres do
table "topics"
repo(ContentCove.Repo)
end
admin do
table_columns [
:name,
:slug,
:path,
:score,
:parent_id,
:inserted_at,
:updated_at,
:created_by_id,
:updated_by_id
]
end
actions do
defaults [:read, :destroy]
default_accept [:name, :score, :parent_id]
create :create do
change {ContentCove.Changes.Slugify, source: :name, target: :slug}
change relate_actor(:created_by)
change relate_actor(:updated_by)
end
end
attributes do
uuid_primary_key :id
attribute :name, :string do
allow_nil? false
end
attribute :slug, :ci_string do
allow_nil? false
writable? false
constraints casing: :lower
end
attribute :score, :float do
default 0.0
end
create_timestamp :inserted_at
update_timestamp :updated_at
end
relationships do
belongs_to :created_by, ContentCove.Accounts.User, allow_nil?: false
belongs_to :updated_by, ContentCove.Accounts.User, allow_nil?: false
belongs_to :parent, ContentCove.Articles.Topic, allow_nil?: true
end
calculations do
calculate :path,
{:array, :ci_string},
{ContentCove.Calculations.Path, keys: [parent: [:slug, :name]]}
end
identities do
identity :unique_name, [:name]
end
end
Thanks