0

我有一张user_relations桌子。

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

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

有没有这样做的rails方式?

这是 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
4

3 回答 3

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
于 2013-05-02T11:33:10.840 回答
1

如果它有类似的东西

has_many: related_users, foreign_key: related_user_id

您可以添加dependent: destroy,当该行被删除时,它也会破坏用户

于 2013-05-02T11:19:11.990 回答
0

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

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

进而:

result.destroy_all
于 2013-05-02T11:17:42.743 回答