0

我正在构建一个 Ruby On Rails API 来帮助管理构建文档——有许多不同类型的文档都有不同的字段,所以我目前有一个模型。

但是,我也希望能够引用这些文档,因为每个文档可以有任意数量的关联文档,这些文档可以是任何文档类型。我希望能够写出类似的东西

class Drawing < ApplicationRecord
  ...

  has_many :associated_documents

我所需要的只是相关文档的名称、ID 和类型(本质上是为了让人们可以轻松地在前端的相关文档之间导航)

这是单表继承的用例吗?有没有办法用多态关联来做到这一点?由于前端用例是链接列表,我应该只存储链接吗?

4

1 回答 1

0

鉴于您具有可以关联任意类(文档)的 M:M 关系,我认为您会查看双面多态关联。

您可能有一个DocumentAssociation类,例如:

# == Schema Information
#
# Table name: document_associations
#
#  id                         :integer          not null, primary key
#  base_document_type         :string
#  base_document_id           :integer
#  associated_document_type   :string
#  associated_document_id     :integer
#  created_at                 :datetime         not null
#  updated_at                 :datetime         not null
#
class DocumentAssociation < ApplicationRecord
  belongs_to :base_document,        polymorphic: true
  belongs_to :associated_document,  polymorphic: true
end

然后是这样的:

class Drawing < ApplicationRecord
  has_many :base_document_associations, class_name: 'DocumentAssociation', as: :base_document
  has_many :associated_documents, through: :base_document_associations
end

这可能在方向上是正确的,但是您可能需要做一些摆弄。如果您希望能够在两个方向上导航(即,对于给定的绘图,您需要绘图既是 base_document 又是 associated_document 的所有关联),您还必须做一些额外的提升。

于 2018-08-22T23:47:09.117 回答