ruby-on-rails - 自引用 has_many :through with customized :primary key issue

标签 ruby-on-rails ruby database-design activerecord

我正在尝试在我的 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/

相关文章:

ruby-on-rails - 使用rails-composer,根据构建器版本获取错误

ruby-on-rails - 带有保留关键字的模型

ruby-on-rails - 如何使普通的 ruby​​ 对象可分配为事件记录关联

mysql - 显示查找表 ID 中的名称 - 设计 Q

mysql - 将数组保存为字符串还是使用多个表?

ruby-on-rails - 在 Rails 中排序 : SQLite vs PostgreSQL

ruby-on-rails - Rails 5 使用事件记录选择第三个模型上没有 id 引用的位置

Ruby 三元 - 警告 : string literal in condition

performance - MongoDB 嵌入式与大数据文档的引用模式

ruby-on-rails - Rails - 关联上的渴望加载关联