Cascading delete and pub_sub
Hi @everyone,
I have a resource (Notification)
```elixir
defmodule App.Notifications.Notification do
use Ash.Resource,
....
postgres do
table "notifications"
repo CauseBeacon.Repo
references do
....
reference :message, on_delete: :delete, index?: false
....
end
end
pub_sub do
module CauseBeaconWeb.Endpoint
prefix "notifications"
transform fn pub_sub_notification ->
Map.take(pub_sub_notification.data, [:id, :user_id, :message_id, :activity_id])
end
publish :create, ["created", :user_id]
publish :mark_as_read, ["updated", :user_id, :id]
publish :mark_as_unread, ["updated", :user_id, :id]
publish :destroy, ["destroyed", :user_id, :id]
end
relationships do
...
belongs_to :message, CauseBeacon.Notifications.Message,
allow_nil?: true,
public?: true
end
...
end
When I delete a Message, it also deletes the Notification. BUT it seems to not generate the pub_sube notification. Did I forget something specific in my code ?
Regards,
Angy.
7 Replies
this is because the destroy is being handled by the database via a database cascade - not by calling the destroy action of the resource
to resolve this, you'll have to remove the database cascade and use something like https://hexdocs.pm/ash/Ash.Resource.Change.Builtins.html#cascade_destroy/2 in the destroy action for your Messages
I am trying to make it work
in the Notification resource I did:
in the Message resource I did:
But then it fails when trying to hard destroy a message. I have the following message:
@Rebecca Le, i did the in order for the deletion of the notification to be before deletion of the message. what do I do wrong ?
that looks correct to me
oh
you're missing the
change
before cascade_destroy
AHAHAHA
thanks, hard destroy works now.... but still no pub_sub generated by Notifications resources...
you also need
return_notifications?: true
for the cascade_destroy
and yeah I've made that same mistake a few times 😅All working now 🙂 thanks. that was really helpful.
OH, I just realize it was all written in the book!
Solution
anytime 🙂