我正在尝试在我的 Rails 2.3.8 应用程序 (ruby 1.8.7) 中模拟 twitter 模型
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
当我执行 User.first.linked_from 时,这会给我一个“SystemStackError:堆栈级别太深”的错误。我必须使用 :user_id 而不是标准 id 的原因是因为我的主键必须是一个字符串。
我该怎么做才能使关系起作用,以便我可以执行 User.first.linked_from 和 User.first.linked_to?
最佳答案
我认为应该是这样的:
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
被切换了,它创建了一个循环引用。
关于ruby-on-rails - 自引用 has_many :through with customized :primary key issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3114830/