Ruby on rails 依赖=>;:在包含两行';同样的结果';

Ruby on rails 依赖=>;:在包含两行';同样的结果';,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-3.1,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 3.1,我有一张友谊表,它看起来像这样: create_table "friendships", :force => true do |t| t.integer "user_id" t.integer "friend_id" t.integer "status" end 对于创建的每个友谊,将插入两行,并恢复用户id和朋友id。当用户被删除时,友谊也应该被删除。此代码将删除其中一个: has_many :friendships, :dependent =>

我有一张友谊表,它看起来像这样:

  create_table "friendships", :force => true do |t|
    t.integer "user_id"
    t.integer "friend_id"
    t.integer "status"
  end
对于创建的每个友谊,将插入两行,并恢复用户id和朋友id。当用户被删除时,友谊也应该被删除。此代码将删除其中一个:

  has_many :friendships, :dependent => :destroy
但这只会消除一种友谊。在我的友谊模型中,我有以下代码:

  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"
我还有一个用于删除友谊的自定义方法,该方法创建了一个在两个关联对象上都调用destroy的事务

我的解决方案是重写User中的destroy方法,循环遍历它的所有好友关系,并对这些好友调用我的remove方法。这是可行的,但这是一个优雅的解决方案吗?我觉得有一个很好的方法可以做到这一点


谢谢。

最优雅的解决方案是在用户模型上有两种
关系,一种是“此用户的朋友”(您已经拥有),另一种是“称此用户为朋友的用户”。然后在它们两个上设置
: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
这意味着销毁一个用户也会删除引用该用户作为用户id或朋友id的任何友谊记录


不过,在打破友谊记录时删除两个相关对象似乎是个坏主意——破坏友谊通常并不意味着两个朋友都不存在

最优雅的解决方案是在用户模型上有两种
关系,一种是“此用户的朋友”(您已经拥有),另一种是“称此用户为朋友的用户”。然后在它们两个上设置
: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
这意味着销毁一个用户也会删除引用该用户作为用户id或朋友id的任何友谊记录


不过,在打破友谊记录时删除两个相关对象似乎是个坏主意——破坏友谊通常并不意味着两个朋友都不存在

请推荐一个更好的标题。我肯定这叫什么。:)请推荐一个更好的标题。我肯定这叫什么。:)用户不应该被销毁。一份友谊由数据库中的两行组成。几乎没有意识到你实际上得到了正确的答案,谢谢!啊-那么你想破坏友谊的一半(我称你为朋友)也会自动破坏另一半(你称我为朋友)?在这种情况下,您可以在Friendly model.True上使用before_destroy回调方法来实现这一点。have\u many:friendships\u of、:class\u name=>“Friendship”、:foreign\u key=>“friends\u id”、:dependent=>:destroy是不是也这么认为呢?那么你在friendships模型本身上有一个have\u many:friendships定义?我没想到!用户不应该被销毁。一份友谊由数据库中的两行组成。几乎没有意识到你实际上得到了正确的答案,谢谢!啊-那么你想破坏友谊的一半(我称你为朋友)也会自动破坏另一半(你称我为朋友)?在这种情况下,您可以在Friendly model.True上使用before_destroy回调方法来实现这一点。have\u many:friendships\u of、:class\u name=>“Friendship”、:foreign\u key=>“friends\u id”、:dependent=>:destroy是不是也这么认为呢?那么你在friendships模型本身上有一个have\u many:friendships定义?我没想到!