mindok
How to combine polymorphic with references -> on_delete
We have an Ash resource defined as polymorphic:
defmodule MyApp.Location do
use Ash.Resource, data_layer: AshPostgres.DataLayer
postgres do
repo MyApp.Repo
polymorphic? true
end
attributes do
uuid_primary_key :id
attribute :resource_id, :uuid do
allow_nil? false
private? true
end
attribute :x, :float
attribute :y, :float
end
...
That is then used by 2 or 3 other resources, e.g.
defmodule MyApp.Event do
use Ash.Resource, data_layer: AshPostgres.DataLayer
postgres do
repo MyApp.Repo
table "events"
end
attributes do
uuid_primary_key :id
attribute :when, :utc_datetime, allow_nil?: false, default: &DateTime.utc_now/0
attribute :what, :string
attribute :who, :string
end
relationships do
has_one :location, Location do
relationship_context %{data_layer: %{table: "event_locations"}}
destination_attribute :resource_id
end
end
Is it possible to use the references config block somehow to delete Locations when the owning Event is deleted?
If it wasn’t polymorphic, we could do something like this in the Location resource, but given it references a specific relationship it won’t work with a polymorphic resource:
postgres do
repo MyApp.Repo
# polymorphic? true
references do
reference :event, on_delete: :delete
end
end
The obvious (to me) alternative is setting up a destroy action on the Event resource that deletes the associated Location first, but then that has to be repeated for every other resource that may use Location which kinda defeats the purpose of using a polymorphic resource in the first place.
Edit: The destroy action isn’t so easy to get right either - how do you inject the datalayer[:table] context to ensure the delete is applied to the right table?
Marked As Solved
zachdaniel
You can do this to configure the polymorphic relationship.
references do
polymorphic_on_delete :delete
end
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








