如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:13:02  来源:igfitidea点击:

how can I do self-reference with ruby on rails?

ruby-on-railsself-reference

提问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

回答by okysabeni

Also check out this tutorial by Ryan Bates on self referential association here. Hck's answer will work but for me, I need a JOIN table and so I use a has_many through association of Rails. Good luck!

还可以在此处查看Ryan Bates 关于自引用关联的教程。Hck 的答案会起作用,但对我来说,我需要一个 JOIN 表,所以我通过 Rails 的关联使用了 has_many。祝你好运!