pratski
pratski

Reputation: 1488

How to delete friendship from db when a "friend" deletes his account?

I have implemented a friendship model successfully which on creation of a friendship creates two rows in the database.

 # Accept a friend request.
  def self.accept(customer, friend)
    transaction do
      accepted_at = Time.now
      accept_one_side(customer, friend, accepted_at)
      accept_one_side(friend, customer, accepted_at)
    end
  end

  # Update the db with one side of an accepted friendship request.
  def self.accept_one_side(customer, friend, accepted_at)
    request = find_by_customer_id_and_friend_id(customer, friend)
    request.status = 'accepted'
    request.accepted_at = accepted_at
    request.save!
  end

Now when User A deletes his account, how do I make sure that the entire friendship (both rows) from the db are also deleted. I believe dependent: destroy will only delete the data related to the User A after deleting his account. But I'd like the other row in the db belonging to User B to be deleted as well.

Upvotes: 0

Views: 130

Answers (1)

Zippie
Zippie

Reputation: 6088

First of all, why do you create two records? That is not that efficient and it's redundant, one record is enough. Check out a great guide here: http://railscasts.com/episodes/163-self-referential-association

Anyways, even in this case it should delete both friendship records, since both id's of your Friendship model are tied to a user twice in two records with a belongs_to, i suppose.

Have you tried it out to see if both will be delete?

If that's not the case (but it should be the case), you could use a before_destroy callback in your User model to delete the other record.

Upvotes: 1

Related Questions