如何使用 ruby on rails 进行自我参考?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6097288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can I do self-reference with ruby on rails?
提问by JRafaelM
I want to self-referentiate a model in a RoR app but, I don't know exactly how. I want to save a linked list where the next node has the id of the previous one. how can I do this rails way? It is a one-to-one relation.
我想在 RoR 应用程序中自我引用模型,但我不知道具体如何。我想保存一个链表,其中下一个节点具有前一个节点的 id。我怎样才能做到这一点?它是一对一的关系。
回答by Hck
The easiest way:
最简单的方法:
class MyModel < ActiveRecord::Base
belongs_to :parent, :class_name => 'MyModel'
has_many :children, :class_name => 'MyModel', :foreign_key => 'parent_id'
end
回答by YaEvan
rails 5
导轨 5
add column xxx_id in users table:
在用户表中添加列 xxx_id:
in migration file:
在迁移文件中:
add_reference :users, :xxx, index: true
and add code in User model
并在用户模型中添加代码
has_many :users, class_name: 'User', foreign_key: 'xxx_id'
belongs_to :manager, class_name: 'User', foreign_key: 'xxx_id'
If you don't have a manager for every user, you need to add optional: true.
如果您没有为每个用户设置经理,则需要添加 optional: true。
'foreign_key' is not necessary. By default this is guessed to be the name of this class in lower-case and “_id” suffixed.
'foreign_key' 不是必需的。默认情况下,这被猜测为小写和“_id”后缀的类的名称。
if foreign_key is user_id, user don't have manager necessary. the result is:
如果foreign_key 是user_id,则用户不需要经理。结果是:
has_many :users, class_name: 'User'
belongs_to :manager, class_name: 'User', optional: true
回答by Vadym Tyemirov
I've spent some time trying to make it work using Rails 3.2.14
我花了一些时间尝试使用 Rails 3.2.14 使其工作
The documentation's suggestion for self-joining associationshasn't worked for belongs_toassociations. Adding a foreign key fixed the issue.
文档对自加入协会的建议对协会不起作用belongs_to。添加外键解决了这个问题。
Class User < ActiveRecord::Base
has_many :invitees, class_name: 'User', foreign_key: :invited_by
belongs_to :host, class_name: 'User', foreign_key: :invited_by
end

