2010-06-25 39 views
5

Tôi đang cố gắng để bắt chước các mô hình twitter trong Rails của tôi 2.3.8 ứng dụng (ruby 1.8.7)tự tham chiếu has_many: thông qua với tùy chỉnh: tiểu học then chốt vấn đề

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 

này mang lại cho tôi một "SystemStackError : stack level too deep "lỗi khi tôi thực hiện User.first.linked_from. Lý do tôi phải sử dụng: user_id thay vì id chuẩn là vì khóa chính của tôi phải là một chuỗi.

Tôi có thể làm gì để làm cho mối quan hệ hoạt động, để tôi có thể thực hiện User.first.linked_from và User.first.linked_to?

Trả lời

7

Tôi tin rằng nó phải như thế này:

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 

trong khi tôi lấy ra một vài điều, có vẻ như bạn :source => :follow:source => :subject được chuyển và nó tạo ra một tham chiếu vòng tròn.

+0

Nó hoạt động. Tuyệt vời! Tôi không bao giờ biết có một phương pháp gọi là set_primary_key. Cảm ơn bạn! – porkeypop

+0

hoạt động. cảm ơn! bạn tiết kiệm thời gian của tôi –

Các vấn đề liên quan