Home > Software engineering >  How to delete an object from postgres that is associated to another
How to delete an object from postgres that is associated to another

Time:07-01

I'm using rails as the ruby web framework. I have an object that is associated to another object. For example: Let's suppose we are creating a Twitter clone on rails where if we delete a Twitter user, we also delete all their Tweets. That will look something like this:

class TwitterAcc < ApplicationRecord 
   has_many :tweets, dependent: :destroy
   belongs_to :user
end

This code snippet means that if we delete a user's Twitter account, then we should delete all their tweets. How would we delete a Twitter account without deleting their tweets?

class TwitterAcc < ApplicationRecord 
   has_many :tweets
   belongs_to :user
end

This code snippet ^^^ wouldn't work. It would throw this error "ActiveRecord::InvalidForeignKey"

CodePudding user response:

The issue is that (if things are right) you have a foreign key between your TwitterAcc table and the tweets. So one tweet record CANOT have a tweeter_acc_id that is not existing. Which is the case if you try to destroy the tweeter_acc. And PSQL isn't happy with that

So you have multiple choices:

  • or you allow your tweets table to keep record of the twitter_acc id, but then you need to remove the foreign key (which is IMO not a good idea)
  • or you allow your tweets table to have a nil value on tweets#twitted_acc_id ( you may need a belongs_to :tweet_acc, optional: true on your Tweet model) and use has_many :tweets, dependent: :nullify on your TweeterAcc model
  • or you only soft delete your tweeter account model, so a soft deleted record becomes "invisible" for your application business logic, but you don't need to deal with the nullable or inexisting FK (https://github.com/jhawthorn/discard)
  • Related