rails + DB dependent destroy vs cascade delete
Hi,
I wanna make sure that child objects also gets deleted when deleting parent.
I'd like to use both dependent: :destroy
(rails side) and on_delete: :cascaade
(db side). Is this a good practice or I should just stick with one. If just one which one should I choose?
has_many :conversations, dependent: :destroy
add_foreign_key "conversations", "users", on_delete: :cascade
The cascade won't call the active record callbacks, which means that it's faster, but if your conversations have other models that you also want to delete, they won't. That's the main drawback there. Usually its best to do dependent: :destroy
even though its a little slower because deletes don't happen that often. If they do in your case, then it might be worth building a custom Service object that can gather up all the necessary records and delete on cascade. That'll give you the benefits of both effectively because you'd be writing the callback logic instead in your service object.
Thanks Chris! I had this problem because of some foreign key constraint + not null combination in the db (without cascade delete), therefore parent couldn't be destroyed without destroying the child.
Then I will only keep the dependent: :destroy
. I wanted to use both (like I do with validate presence
and null: false
) to make sure everything is synced, but it's not a good practice then in this case.
It would be great to see an episode on this. I mean something like 3-4 models that depend on each other, and the different options how this can be handled both on rails and DB side. For a simple instance there is a post and comment model and both have user_id. What if commenter deletes his account, but his old comments should be kept. If sby goes on the post page then it will raise an error since the commenter for that given comment doesn't exist anymore. (Because of this at the moment I have a dependent: :destroy
chain on everything to make sure the app works fine.)
Great idea. Might also make sense to include something there on deleted records that use like an DeletedUser
class or something to display some sort of text instead. Reddit does something like this when you see the posts that show [deleted]
as someone's username.