2路删除关系

时间:2013-05-02 11:06:59

标签: ruby-on-rails

我有一张user_relations表。

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

当我销毁行(1 | 15)时,我希望rails自动删除并行行(15 | 1)

有这种做法吗?

这是user_relation类:

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

3 个答案:

答案 0 :(得分:3)

是的,你可以在UserRelation模型中编写一个过滤器,

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

更新

要创建关联记录,您可以编写一个这样的过滤器,

 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

答案 1 :(得分:1)

如果有类似

的内容

has_many: related_users, foreign_key: related_user_id

您可以添加dependent: destroy,当删除此行时,它也会销毁用户

答案 2 :(得分:0)

我认为您可以选择这两行:

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

然后:

result.destroy_all