Rails 5 - 具有 2 个字段引用同一对象的模型
Rails 5 - model with 2 fields referring to same object
在我为学习 RoR 而构建的应用程序中,我有一个模型 "Document" 和一个模型 "Business Partner"。在 "Document" 模型上,我有 2 个字段("Sender" 和 "Receiver")引用模型 "Business Partner"。
如何使用不同字段对同一目标建模两次 belongs_to?迁移应该是什么?
相关问题:如何为业务合作伙伴建立与 it self 的关系模型?即一家公司有很多商业伙伴,但也可以是一个商业伙伴。注意 - 不是同一条记录(公司 A 不能与公司 A(本身)有关系。
假设您在 Document
模型(即 documents
table 上有用于发送方和接收方关系的列 sender_id
和 receiver_id
),你可以这样做:
class Document < ActiveRecord::Base
belongs_to :sender, class_name: "BusinessPartner"
belongs_to :receiver, class_name: "BusinessPartner"
end
只要您在 table 上有这些列,就没有特别的迁移(如果您将它们命名为其他名称,只需替换 sender
和 receiver
上面的任何列名减去 _id
部分)。
然后对于您的 BusinessPartner
模型:
class BusinessPartner < ActiveRecord::Base
has_many :sent_documents, class_name: "Document", foreign_key: "sender_id"
has_many :received_documents, class_name: "Document", foreign_key: "receiver_id"
end
此处,sent_documents
将获取 documents
table 中的所有行,其中 sender_id
与 BusinessPartner
的 id 相匹配,对于 received_documents
.
Rails docs 中的更多信息。
关于您的第二个问题,section of the Rails docs describing this, it is called "Self Joins". However, given that you want to model a many-to-many relationship, you will need a slightly special table arrangement. See this SO answer 提供了有关如何设置该安排的一些详细信息。这本身实际上是一个有点棘手的话题,如果您对细节感兴趣,我建议您针对它提出一个单独的问题(尽管 SO post 回答得很好)。
在我为学习 RoR 而构建的应用程序中,我有一个模型 "Document" 和一个模型 "Business Partner"。在 "Document" 模型上,我有 2 个字段("Sender" 和 "Receiver")引用模型 "Business Partner"。
如何使用不同字段对同一目标建模两次 belongs_to?迁移应该是什么?
相关问题:如何为业务合作伙伴建立与 it self 的关系模型?即一家公司有很多商业伙伴,但也可以是一个商业伙伴。注意 - 不是同一条记录(公司 A 不能与公司 A(本身)有关系。
假设您在 Document
模型(即 documents
table 上有用于发送方和接收方关系的列 sender_id
和 receiver_id
),你可以这样做:
class Document < ActiveRecord::Base
belongs_to :sender, class_name: "BusinessPartner"
belongs_to :receiver, class_name: "BusinessPartner"
end
只要您在 table 上有这些列,就没有特别的迁移(如果您将它们命名为其他名称,只需替换 sender
和 receiver
上面的任何列名减去 _id
部分)。
然后对于您的 BusinessPartner
模型:
class BusinessPartner < ActiveRecord::Base
has_many :sent_documents, class_name: "Document", foreign_key: "sender_id"
has_many :received_documents, class_name: "Document", foreign_key: "receiver_id"
end
此处,sent_documents
将获取 documents
table 中的所有行,其中 sender_id
与 BusinessPartner
的 id 相匹配,对于 received_documents
.
Rails docs 中的更多信息。
关于您的第二个问题,section of the Rails docs describing this, it is called "Self Joins". However, given that you want to model a many-to-many relationship, you will need a slightly special table arrangement. See this SO answer 提供了有关如何设置该安排的一些详细信息。这本身实际上是一个有点棘手的话题,如果您对细节感兴趣,我建议您针对它提出一个单独的问题(尽管 SO post 回答得很好)。