【问题标题】:Many-to-Many relation using Mongoid database-design?使用 Mongoid 数据库设计的多对多关系?
【发布时间】:2012-06-16 11:37:51
【问题描述】:

我尝试实现以下数据库结构,但在理解如何使用 mongoid 时遇到问题:

我有一个模型 Documents、一个模型 DocumentTeam 和一个模型 Employees。用户可以创建文档并可以选择员工,这些员工将添加到 DocumentTeam。这是我的atm:

class Document
  embeds_one :document_team
end

class DocumentTeam
  has_many :employees
  embedded_in :document
end

class Employee
  belongs_to :document_teams
end

所以我的问题是:我如何告诉 Rails 在创建文档时自动将选定的员工插入到嵌入式 DocumentTeam 中?

此外,我希望能够列出例如员工的所有简报

Employee.first.documents

这也可能吗?

提前感谢!

【问题讨论】:

  • 如果您能提及简报与其他文件的关系以及您如何选择所选员工会更好?
  • 查看编辑。粘贴了错误的代码!

标签: ruby-on-rails database-design mongoid


【解决方案1】:

在 mongoid 中你不能引用嵌入的文档。您可以从嵌入文档中引用根文档,但反之则不行。即你不能在Employee 中有belongs_to :document_teams。此外,一个副作用是嵌入文档中的关系应该是单面的。您可以将您的建模更改为以下以实现您想要的:

class Document
  embeds_one :document_team
end

class DocumentTeam
  has_and_belongs_to_many :employees, inverse_of: nil
  embedded_in :document
end

class Employee
  def documents
    Document.where('document_team.employee_ids' => self.id)
  end
end

这将允许您使用Employee.first.documents,但您不能将其视为关系并继续执行您可以对关系执行的操作,例如重新分配、推送和拉取文档。您必须通过DocumentTeam 管理团队和员工关系,但可以直接访问员工文档以供阅读。

PS:Document id 不是类的好名字,我猜它在某些情况下可能会与 Mongoid::Document 冲突。

【讨论】:

    猜你喜欢
    • 2012-09-30
    • 2011-05-01
    • 2011-04-13
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    相关资源
    最近更新 更多