如何在 RoR 中将多个不同类型的元素相互链接?
我有事件、文档和调查,它们都需要能够相互链接,我计划建立一个包含四列的链接表,如下所示:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您只是在寻找
has_many
和belongs_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
andbelongs_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 linehas_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.