自引用 has_many :through 和自定义 :primary key 问题

2024-02-05

我正在尝试在 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 and :source => :subject被切换并创建了循环引用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自引用 has_many :through 和自定义 :primary key 问题 的相关文章

随机推荐