如何在 ActiveRecord 中建立自反自联接关系? [英] How do I do reflexive self-join relationships in ActiveRecord?

查看:21
本文介绍了如何在 ActiveRecord 中建立自反自联接关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实施一种社交网络风格的友谊模型,但我没有太多运气试图找出可用的插件.我想如果我自己做,我会更好地学习 Rails.所以这就是我所拥有的:

I'm trying to implement a social networking style friendship model and I didnt have much much luck trying to figure out the plugins available out there. I think I'll learn Rails better if I do it myself. So here's what I have :

class User < ActiveRecord::Base
  has_many :invitee_friendships ,
           :foreign_key => :friend_id,
           :class_name => 'Friendship'

  has_many :inviter_friends,
            :through => :invitee_friendships

  has_many :inviter_friendships ,
           :foreign_key => :user_id,
           :class_name => 'Friendship'

  has_many :invited_friends,
            :through => :inviter_friendships

end

class Friendship < ActiveRecord::Base
  belongs_to :user
  //I think something needs to come here, i dont know what
end

irb 中,当我尝试此操作时:

In irb when I try this:

friend1  = Friend.create(:name => 'Jack')
friend2  = Friend.create(:name => 'John')
bff = Friendship.create(:user_id =>1, :friend_id => 2)
f1.invited_friends

我收到一个错误:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError:
Could not find the source
association(s) :invited_friend or
:invited_friends in model Friendship. 
Try 'has_many :invited_friends,
:through => :invited_friendships,
:source => <name>'.  Is it one of
:user?

友谊系统的扩展:

  • 用户可以邀请其他用户成为朋友.
  • 您邀请成为朋友的用户由 invited_friends 表示.
  • 邀请您成为朋友的用户由 inviter_friends 表示.
  • 您的好友总数由invited_friends + inviter_friends 表示.
  • A user can invite other users to become friends.
  • Users who you invited to become friends are represented by invited_friends.
  • Users who invited you to become friends are represented by inviter_friends.
  • Your total friend list is represented by invited_friends + inviter_friends.

架构

table Friendship
      t.integer :user_id
      t.integer :friend_id
      t.boolean :invite_accepted
      t.timestamps

table User
    t.string :name
    t.string :description

推荐答案

我很惊讶没有人指出最近 Ryan Bates 的 截屏 主题 :)

I'm surprised no one has pointed to the recent Ryan Bates's screencast on the topic :)

希望这有帮助!.

摘自 Ryan '...需要在 User 模型上进行自引用关联来定义朋友/关注者'

Excerpt from Ryan '... requires a self-referential association on the User model to define friends/followers'

这篇关于如何在 ActiveRecord 中建立自反自联接关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆