如何在 RoR 中将多个不同类型的元素相互链接?

发布于 2024-08-23 04:53:24 字数 283 浏览 6 评论 0原文

我有事件、文档和调查,它们都需要能够相互链接,我计划建立一个包含四列的链接表,如下所示:

link_elements{
  element1_type CHAR(1)
  element1_id INTEGER
  element2_type CHAR(1)
  element2_id INTEGER
}

问题是我不知道如何在 RoR 中制作模型这样我就可以使用元素类型字段来识别相应元素 id 属于哪个表(文档、事件或调查)。我对 Ruby 很陌生,如果有任何帮助,我将不胜感激。

I have Events, Documents, and Surveys which all need to be able to link to one another, I was planning on having a linking table with four columns as follows:

link_elements{
  element1_type CHAR(1)
  element1_id INTEGER
  element2_type CHAR(1)
  element2_id INTEGER
}

The problem is I can't figure out how to make the model in RoR so that I can use the element type field to identify which table the corresponding element id belongs to (Documents, Events, or Surveys). I'm really new to Ruby and any help would really be appreciated.

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

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

发布评论

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

评论(1

嗫嚅 2024-08-30 04:53:24

我认为您只是在寻找 has_manybelongs_to 关联。

如果您有事件模型、文档模型和调查模型,则可以在模型文件夹中各自的 .rb 文件中指定它们是否具有或属于其他模型。

例如:您希望调查属于文档。在 Survey.rb 中,添加行 belongs_to :document。在 Document.rb 中,添加行 has_many :surveys

现在,如果您在 Surveys 表中添加新的“document_id”列,它将查找与该列中的 id 整数相对应的 Document 对象。

有关详细信息,请查看 Rails API

I think you're just looking for the has_many and belongs_to associations.

If you have an Event model, a Document model, and a Survey model, then you can specify in their respective .rb files in the Models folder if they have or belong to the other models.

Ex: you want Surveys to belong to Documents. In Survey.rb, add the line belongs_to :document. In Document.rb, add the line has_many :surveys.

Now if you add a new "document_id" column in the Surveys table, it will look for a a Document object that corresponds to the id integer in that column.

For more info check out the Rails API.

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