如何在 Rails 中为具有多个链接的项目配置模型 ActiveRecord

发布于 2024-11-25 20:59:04 字数 419 浏览 6 评论 0原文

我有两个模型,项目和链接。每个链接都会将两个项目连接在一起,只有两个。建立模型关系的最佳方式是什么?

我目前有这个:

class Item < ActiveRecord::Base
  has_many  :links
end


class Link < ActiveRecord::Base
  belongs_to :item1, :class_name => "Item", :foreign_key => "item1_name"
  belongs_to :item2, :class_name => "Item", :foreign_key => "item2_name"
end

这是正确的吗?当我想列出每个项目的链接时,以后会遇到任何问题吗?

请推荐我更好的选择,谢谢。

I have two models, Item and Link. Each link is going to join two items together, only two. What is the best way to set up the model relationship?

I currently have this:

class Item < ActiveRecord::Base
  has_many  :links
end


class Link < ActiveRecord::Base
  belongs_to :item1, :class_name => "Item", :foreign_key => "item1_name"
  belongs_to :item2, :class_name => "Item", :foreign_key => "item2_name"
end

Is this correct? Will I run into any problems later on when I wanted to list the links for each item?

Please recommend me better alternatives, Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

清晨说晚安 2024-12-02 20:59:05

看看有一个

类似的东西

Item

:has_one :item, through: :links

应该通过链接模型将两个项目链接在一起

take a look at has one through

Something like

Item

:has_one :item, through: :links

That should link two items together through the links model

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