ActiveRecord에서 반사적 인 자기 합의 관계를 어떻게 수행합니까?
-
06-07-2019 - |
문제
저는 소셜 네트워킹 스타일 우정 모델을 구현하려고 노력하고 있으며 사용 가능한 플러그인을 알아내는 데 많은 운이 없었습니다. 내가 직접한다면 레일을 더 잘 배울 것이라고 생각합니다. 그래서 여기에 내가 가진 것이 있습니다.
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
내가 이것을 시도 할 때 :
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
.
개요
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의 스크린 캐스트 주제에 :)
도움이 되었기를 바랍니다!.
Ryan의 발췌 '... 친구/팔로워를 정의하기 위해 사용자 모델에 대한 자기 참조 협회가 필요합니다.
제휴하지 않습니다 StackOverflow