【问题标题】:Is there a better way to structure these database tables?有没有更好的方法来构建这些数据库表?
【发布时间】:2013-05-22 04:36:03
【问题描述】:

我正在努力寻找在一个新的 Rails 应用程序上设计/查询我的数据库的最佳方法。这就是我现在所拥有的:

documents:
  title
  has_many :document_sections

document_sections:
  belongs_to :document
  habtm :resources

resources_document_sections:
  belongs_to :resource
  belongs_to :document_section

resources:
  text

所以说document_section.resources 很容易。但是document.resources给我带来了麻烦

到目前为止,我发现的唯一方法是收集文档部分 ID,然后运行第二个查询:

d = Document.last
s_ids = d.document_section_ids

Resource.joins(:document_sections)
        .where(document_sections: { id: s_ids })
        .uniq

所以这开始很糟糕,随着查询变得越来越复杂,情况会变得更糟。每次碰上这段感情,我都觉得很头疼。

我想知道在布置这些表时是否可以遵循不同的模式,这样查询它们就不会那么令人头疼了?还是我缺少更好的查询策略?

【问题讨论】:

    标签: sql ruby-on-rails database-design activerecord


    【解决方案1】:

    您的文档没有任何关系。您需要向关系中的两个模型添加一些东西,您不能只将它添加到document_sections 并期望documents 与任何东西有任何关系。

    您需要在文档中添加has_many ... through:

    class Document < ActiveRecord::Base
      has_many :document_sections
      has_many :relationships, through: :document_sections
    end
    

    【讨论】:

    • 抱歉,我忘记在文档中添加has_manyhas_many :through 完全符合我的要求,不过……我很惊讶!出于某种原因,我认为它不会跟踪多对多关系。谢谢!
    猜你喜欢
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多