如何使用 ruby​​ on Rails 进行自引用?

发布于 2024-11-09 04:11:53 字数 90 浏览 2 评论 0原文

我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寒江雪… 2024-11-16 04:11:53

最简单的方法:

class MyModel < ActiveRecord::Base
  belongs_to :parent, :class_name => 'MyModel'
  has_many :children, :class_name => 'MyModel', :foreign_key => 'parent_id'
end

The easiest way:

class MyModel < ActiveRecord::Base
  belongs_to :parent, :class_name => 'MyModel'
  has_many :children, :class_name => 'MyModel', :foreign_key => 'parent_id'
end
栀子花开つ 2024-11-16 04:11:53

Rails 5

在用户表中添加列 xxx_id:

在迁移文件中:

add_reference :users, :xxx, index: true

并在用户模型中添加代码

has_many :users, class_name: 'User', foreign_key: 'xxx_id'
belongs_to :manager, class_name: 'User', foreign_key: 'xxx_id'

如果您没有每个用户的经理,则需要添加可选:true。

“foreign_key”不是必需的。默认情况下,这被猜测为该类的小写名称并带有“_id”后缀。

如果foreign_key是user_id,则用户不需要manager。
结果是:

has_many :users, class_name: 'User'
belongs_to :manager, class_name: 'User', optional: true

它们被称为 自连接

rails 5

add column xxx_id in users table:

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.

'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:

has_many :users, class_name: 'User'
belongs_to :manager, class_name: 'User', optional: true

They are called self-joins

赏烟花じ飞满天 2024-11-16 04:11:53

我花了一些时间尝试使用 Rails 3.2.14 使其工作

文档对 self 的建议-加入关联对于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

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.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文