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

Answers


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

Need Your Help

aspxGridView disappears when showing javascript alert but reappears when alert is closed

asp.net .net aspxgridview

I have an usercontrol with an aspxGridview inside it. I use this usercontrol in my page in a separate updatepanel (named updListView). In another update panel (updForm) I have a button and its code

Delphi> Vertical scanline? (Get columns instead of rows?)

delphi image-processing

I'm trying to write an algorithm that will detect the space between 'RF' and 'WOOLF in the image below. I need something like Scanline for COLUMNS not rows. My algorithm will be scanning each col...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.