自我指涉的has_many:通过与定制:主键的问题 [英] Self-referential has_many :through with customized :primary key issue

查看:145
本文介绍了自我指涉的has_many:通过与定制:主键的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图效仿Twitter的模式在我的Rails 2.3.8应用程序(红宝石1.8.7)

I'm trying to emulate the twitter model in my Rails 2.3.8 app (ruby 1.8.7)

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

这给了我一个SystemStackError:堆栈层次过深的错误,当我做User.first.linked_from。我之所以要使用:USER_ID代替标准号是因为我的主键必须是一个字符串

This gives me a "SystemStackError: stack level too deep" error when I do User.first.linked_from. The reason I have to use :user_id instead of the standard id is because my primary key has to be a string.

我能做些什么使关系的工作,这样我可以做User.first.linked_from和User.first.linked_to?

What can I do to make the relation work, so that I can do User.first.linked_from and User.first.linked_to?

推荐答案

我相信它应该是这样的:

I believe it should be like this:

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

而我删除了一些东西,它看起来像你的:源=&GT; :遵循:源=&GT; :受进行切换,并创建了一个循环引用

while I removed a few things, it looks like your :source => :follow and :source => :subject were switched and it created a circular reference.

这篇关于自我指涉的has_many:通过与定制:主键的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆