如何使用 ruby on Rails 进行自引用?
我想在 RoR 应用程序中自我引用模型,但是我不知道具体如何操作。我想保存一个链表,其中下一个节点具有前一个节点的 id。我怎样才能做到这一点?这是一种一对一的关系。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法:
The easiest way:
Rails 5
在用户表中添加列 xxx_id:
在迁移文件中:
并在用户模型中添加代码
如果您没有每个用户的经理,则需要添加可选:true。
“foreign_key”不是必需的。默认情况下,这被猜测为该类的小写名称并带有“_id”后缀。
如果foreign_key是user_id,则用户不需要manager。
结果是:
它们被称为 自连接
rails 5
add column xxx_id in users table:
in migration file:
and add code in User model
If you don't have a manager for every user, you need to add 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.
if foreign_key is user_id, user don't have manager necessary.
the result is:
They are called self-joins
我花了一些时间尝试使用 Rails 3.2.14 使其工作
文档对 self 的建议-加入关联对于
belongs_to
关联不起作用。添加外键解决了这个问题。I've spent some time trying to make it work using Rails 3.2.14
The documentation's suggestion for self-joining associations hasn't worked for
belongs_to
associations. Adding a foreign key fixed the issue.