加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:26:22 所属栏目:百科 来源:网络整理
导读:我试图在我的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_i
我试图在我的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 => :主题被切换,它创建了一个循环引用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读