2

所以我有一个如下所示的友谊表:

  create_table "friendships", :force => true do |t|
    t.integer "user_id"
    t.integer "friend_id"
    t.integer "status"
  end

对于创建的每个友谊,插入两行,其中 user_id 和friend_id 恢复。当一个用户被删除时,友谊也应该被删除。此代码删除其中之一:

  has_many :friendships, :dependent => :destroy

但这只会消除其中一种友谊。在我的友谊模型中,我有以下代码:

  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"

我还有一个用于删除友谊的自定义方法,它会创建一个在两个关联对象上调用destroy 的事务。

我的解决方案是覆盖 User 中的 destroy 方法并遍历其所有友谊并在它们上调用我的 remove 方法。这行得通,但它是一个优雅的解决方案吗?我觉得可能有一个不错的 Rails 方式来做到这一点。

谢谢。

4

1 回答 1

0

最优雅的解决方案是has_many在 User 模型上有两个关系,一个用于“此用户的朋友”(您已经有了),另一个用于“称该用户为朋友的用户”。然后设置:dependent => :destroy他们两个:

def User
    # Friends of this user
    has_many :friendships, :dependent => :destroy
    has_many :friends, :through => :friendships

    # Users who call this user a friend
    has_many :friendships_of, :class_name => "Friendship", :foreign_key => "friend_id", :dependent => :destroy
    has_many :friends_of, :through => :friendships_of
end

这意味着销毁用户也会删除引用该用户作为 user_id 或friend_id 的任何友谊记录。

不过,在打破友谊记录时移除两个关联对象似乎是个坏主意 - 破坏友谊通常并不意味着两个朋友都不复存在!

于 2011-06-28T14:25:30.943 回答