ruby-on-rails – 自我引用has_many:通过自定义:主键问题

我试图在我的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',:class_name => 'User'
end

class User < ActiveRecord::Base
  has_many :relations_to,:class_name => 'Connection'
  has_many :relations_from,: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:stack level too deep”错误.我必须使用的原因:user_id而不是标准id是因为我的主键必须是一个字符串.

我可以做些什么来使关系工作,以便我可以做User.first.linked_from和User.first.linked_to?

解决方法

我相信它应该是这样的:

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

class User < ActiveRecord::Base
  set_primary_key "user_id"

  has_many :relations_to,:source => :follow 
  has_many :linked_to,:source => :subject
end

虽然我删除了一些东西,但它看起来像你的:source => :follow and:source => :主题被切换,它创建了一个循环引用.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...