How do we handle deletion dependencies here? E.g. say I setup an event to be trigged on a `comment` creation, or when I upload an image. But what happens when I delete that comment or I delete that image. Ideally, I would like to be able to delete the event that is related to that specific recently deleted comment or image.
What's the best way to do this?
This is a fantastic question. If you setup the reverse dependency and set the dependent destroy option, that will delete the events when you delete the comment.
has_many :events, as: :eventable, dependent: :destroy
Ahh perfect. So that covers most use-cases. How do I handle virtual attributes, e.g. 'votes'. So I am using acts_as_votable, which creates a bunch of virtual attributes to indicate when a user has `liked` a `Node`. When that node is deleted, all of those virtual attributes are deleted, so I would like to delete all of those events too.
Do I have to do this manually in an `after_delete :callback` on my `Node` model or is there some other way?
Depending on how that's setup, you might patch the Vote model so that if you created events matched to the vote, you could delete those. You can't really set this up on virtual attributes because you need it attached directly to the records so when things get deleted you can remove the related records.
Yeh....so I guess the solution just may be in the removal of the Node callback. Or just adding the `dependent: :destroy` on my Node model. Or maybe I just ignore it, given that it is just a like.
I have my events set up. Some of the models I have are listings and reviews. Reviews belong to listings. If someone leaves a review for a listing, the event saves both the review id (as eventable_id) and the listing id (as parent_id). So I can link to both in the view.
My problem is that if I deleted the listing, the review event remains, and rails throws an error (can't find listing with id 25, for example).
Here is my listing model:
class Listing < ApplicationRecord belongs_to :user has_many :reviews, dependent: :destroy has_many :activities, as: :eventable, dependent: :destroy
My reviews model also has
has_many :activities, as: :eventable, dependent: :destroy
The issue I'm having is that the listing gets deleted, and the reviews and events associated with that listing get deleted. But the events associated with the reviews do not get deleted. Did I do something wrong in the association?
Is this something where I would need to use a cascade? I do not understand the differences.
*Update, it seems like the immediate events are not being deleted along with the listing as well.
Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.