2010-06-25 2 views
5

내 레일에서 2.3.8 응용 프로그램을 트위터 모델을 모방하기 위해 노력하고있어 (루비 1.8.7)는자기 참조 has_many : 통해 사용자와 : 기본 키 문제

class Connection < ActiveRecord::Base 
    belongs_to :subject, :foreign_key => 'subject_id', :primary_key => 'user_id', :class_name => 'User' 
    belongs_to :follower, :foreign_key => 'follower_id', :primary_key => 'user_id', :class_name => 'User' 
end 

class User < ActiveRecord::Base 
    has_many :relations_to, :primary_key => 'user_id', :foreign_key => 'follower_id', :class_name => 'Connection' 
    has_many :relations_from, :primary_key => 'user_id', :foreign_key => 'subject_id', :class_name => 'Connection' 
    has_many :linked_from, :through => :relations_from, :source => :subject, :primary_key => 'user_id' 
    has_many :linked_to, :through => :relations_to, :source => :follower, :primary_key => 'user_id' 
end 

이 나에게 "SystemStackError을 제공합니다 : Stack level too deep "오류가 발생합니다. User.first.linked_from. 내 기본 키가 문자열이어야하기 때문에 표준 ID 대신 user_id를 사용해야하는 이유가 있습니다.

관계가 작동하도록하려면 어떻게해야 User.first.linked_from과 User.first.linked_to를 할 수 있습니까?

답변

7

나는 그것이 이렇게 될 전망이다 : 나는 몇 가지를 제거하면서

class Connection < ActiveRecord::Base 
    belongs_to :subject, :class_name => 'User' 
    belongs_to :follower, :class_name => 'User' 
end 

class User < ActiveRecord::Base 
    set_primary_key "user_id" 

    has_many :relations_to, :foreign_key => 'follower_id', :class_name => 'Connection' 
    has_many :relations_from, :foreign_key => 'subject_id', :class_name => 'Connection' 
    has_many :linked_from, :through => :relations_from, :source => :follow 
    has_many :linked_to, :through => :relations_to, :source => :subject 
end 

, 그것은 당신의 :source => :follow:source => :subject가 전환 것처럼 보이는이 순환 참조를 만들었습니다.

+0

작동합니다. 굉장해! set_primary_key라는 메서드가 있다는 것을 전혀 알지 못했습니다. 감사합니다. – porkeypop

+0

작동합니다. 감사! 너는 내 시간을 절약한다. –

관련 문제