Noam B.
Noam B.

Reputation: 3250

2 way delete relationship

I have a user_relations table.

user_id | related_user_id
-------------------------
  1     | 15
  1     | 17
  4     | 56
 15     |  1
  5     | 34

When I destroy the row (1 | 15), I want rails to automatically delete the parallel row (15 | 1).

Is there a rails way of doing this?

This is the user_relation class:

class UserRelation < ActiveRecord::Base
  belongs_to :user, :class_name => "User", :foreign_key => "user_id"
  belongs_to :related_user, :class_name => "User", :foreign_key => "related_user_id"
end

Upvotes: 0

Views: 81

Answers (3)

maximus ツ
maximus ツ

Reputation: 8065

Yes, you can write a filter to do so in UserRelation model,

after_destroy :delete_associated


def delete_associated 
 ur = UserRelations.find_by_related_user_id_and_user_id(related_user_id, user_id)
 ur.delete if ur
end

Update:

To create associated record you can write a filter like this,

 after_create :create_associated
 def create_associated
   UserRelations.find_or_create_by_related_user_id_and_user_id(related_user_id, user_id) #check if already exist or create new
 end

Upvotes: 3

Anezio Campos
Anezio Campos

Reputation: 1555

If it have something like

has_many: related_users, foreign_key: related_user_id

You could add dependent: destroy and when this row is deleted it will also destroy the user

Upvotes: 1

digitalWestie
digitalWestie

Reputation: 2797

I think you could select both those rows with:

result = UserRelation.where(:user_id => [1,15]).where(:related_user_id => [1,15])

And then:

result.destroy_all

Upvotes: 0

Related Questions